• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

savedRequest.getRedirectUrl()가 null이 들어가서 로그인 후 localhost:8080/null이 나옵니다

22.07.20 13:52 작성 조회수 422

0

안녕하세요.

localhost:8080/로 들어가서 나오는 시큐리티의 기본 로그인 페이지에서 아무 계정으로 로그인을 하면 localhost:8080/null이 나옵니다. localhost:8080/login로 request를 보냈을떄도 로그인을 하면 localhost:8080/null이 나옵니다

response header를 보면

Location: http://localhost:8080/null

로 나와있고 디버그시에도 savedRequest가 null인게 확인되는데 로그인전에 request로 보낸 url이 httpSessionRequestCache에 저장돼서 로그인 이후 제대로 이동하려면 뭘 수정해야되나요?

logout이나 rememberme같은 부차적인 요소들은 가독성을 위해 생략했습니다.

밑에는 코드입니다.

    // 메모리 방식으로 사용자를 생성하는 configure()는 생략함    

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/admin/pay").hasRole("ADMIN")
                .antMatchers("/admin/**").access("hasRole('ADMIN') or hasRole('SYS')")
                .anyRequest().authenticated();

        http
                .formLogin()
//                .loginPage("/loginPage") 
                .defaultSuccessUrl("/", true)
                .failureUrl("/login")
                .usernameParameter("userId")
                .passwordParameter("passwd")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println("authentication:"+authentication.getName());

                        // savedRequest가 null로 전달되는게 문제!
                        RequestCache requestCache=new HttpSessionRequestCache();
                        SavedRequest savedRequest=requestCache.getRequest(request,response);
                        String redirectUrl=savedRequest.getRedirectUrl();
                        response.sendRedirect(redirectUrl); 
                    }
                })
                .permitAll();

        // http.logout() 생략
       // http.rememberMe() 생략   
       // http.sessionManagement() 생략

       http.exceptionHandling()
//              .authenticationEntryPoint(new AuthenticationEntryPoint() {
//                    @Override
//                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//                        response.sendRedirect("/login"); 
//                    }
//                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        response.sendRedirect("/denied"); 
                    }
                });
    }

 

@RestController
@RequestMapping("/")
public class SecurityController {
    @GetMapping
    public String index() {
        return "home";
    }
    @GetMapping("loginPage")
    public String loginPage() {
        return "loginPage";
    }
    @GetMapping("user")
    public String user() {
        return "user";
    }
    @GetMapping("admin/pay")
    public String adminPay() {
        return "adminPay";
    }
    @GetMapping("admin/**")
    public String admin() {
        return "admin";
    }

    @GetMapping("login") 
    public String login() {
        return "login";
    }
    @GetMapping("denied") 
    public String denied() {
        return "denied";
    }

}

답변 1

답변을 작성해보세요.

0

제가 테스트를 해보면 정상적으로 동작하는 것 같습니다.

package com.example.demo;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 메모리 방식으로 사용자를 생성하는 configure()는 생략함

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/user").hasRole("USER")
.antMatchers("/admin/pay").hasRole("ADMIN")
.antMatchers("/admin/**").access("hasRole('ADMIN') or hasRole('SYS')")
.anyRequest().authenticated();

http
.formLogin()
// .loginPage("/loginPage")
.defaultSuccessUrl("/", true)
.failureUrl("/login")
.usernameParameter("userId")
.passwordParameter("passwd")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
System.out.println("authentication:"+authentication.getName());

// savedRequest null로 전달되는게 문제!
RequestCache requestCache=new HttpSessionRequestCache();
SavedRequest savedRequest=requestCache.getRequest(request,response);
String redirectUrl=savedRequest.getRedirectUrl();
response.sendRedirect(redirectUrl);
}
})
.permitAll();

// http.logout() 생략
// http.rememberMe() 생략
// http.sessionManagement() 생략

http.exceptionHandling()
// .authenticationEntryPoint(new AuthenticationEntryPoint() {
// @Override
// public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
// response.sendRedirect("/login");
// }
// })
.accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
response.sendRedirect("/denied");
}
});
}
}
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class SecurityController {
@GetMapping
public String index() {
return "home";
}
@GetMapping("loginPage")
public String loginPage() {
return "loginPage";
}
@GetMapping("user")
public String user() {
return "user";
}
@GetMapping("admin/pay")
public String adminPay() {
return "adminPay";
}
@GetMapping("admin/**")
public String admin() {
return "admin";
}

@GetMapping("login")
public String login() {
return "login";
}
@GetMapping("denied")
public String denied() {
return "denied";
}

}

기본적인 계정인 user 와 자동 생성 비밀번호로 로그인 하면 home 으로 이동합니다.

그리고 /user 로 접근하면 denied 가 나옵니다.

동일한 소스로 테스트 한 것인데 위의 null 이 나오는 현상이 재현되지 않아서 질문에 대한 정확한 답변을 드리기가 어렵네요..

디버깅 하시면서 어디서 오류가 발생하는지 소스를 따라가보면서 확인해 보시기 바랍니다.