Spring Security OAuth2 - Handler

목차

참고

Success Handler 만들기

Oauth2 인증 후 특정 작업을 진행하기 위해서는 SuccessHandler 가 필요하다. AuthenticationSuccessHandler 를 구현해 인증 후 사용자 정보를 로그로 출력하는 Handler 를 만들어 보려고 한다.

  • 인증 후 Authentication 객체 내 Principal 에는 OAuth2User 객체 정보가 들어가게 된다. (OAuth2LoginAuthenticationProvider 에서 확인)
@Slf4j
public class Oauth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();

log.info("oAuth2User name = {}", (String) oAuth2User.getAttribute("email"));
log.info("oAuth2User name = {}", (String) oAuth2User.getAttribute("name"));
}
}

Security Config 추가

oauth2AuthenticationSuccessHandler Bean 을 생성 후 successHandler 에 추가한다.

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/oauth_login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/oauth_login")
.successHandler(oauth2AuthenticationSuccessHandler());
}

@Bean
public AuthenticationSuccessHandler oauth2AuthenticationSuccessHandler() {
return new Oauth2AuthenticationSuccessHandler();
}

Failure Handler 만들기

Success Handler 와 마찬가지로 인증 실패시 특정 작업을 실행하기 위해 Failure Handler 가 필요하다. AuthenticationFailureHandler 를 구현해 실패 후 실패 Log 와 response 객체에 인증 실패 메시지를 보내도록 한다.

@Slf4j
@RequiredArgsConstructor
public class Oauth2AuthenticationFailureHandler implements AuthenticationFailureHandler {

private final ObjectMapper objectMapper;

@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {

response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);

log.info("Authentication failed");
objectMapper.writeValue(response.getWriter(), "Authentication failed");

}
}

Security Config 추가

oauth2AuthenticationFailureHandler Bean 을 생성 후 failureHandler 에 넣어준다.

@EnableWebSecurity
@Slf4j
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final OAuth2AuthorizedClientService oAuth2AuthorizedClientService;

private final ObjectMapper objectMapper;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth_login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/oauth_login")
.successHandler(oauth2AuthenticationSuccessHandler())
.failureHandler(oauth2AuthenticationFailureHandler());
}

@Bean
public AuthenticationSuccessHandler oauth2AuthenticationSuccessHandler() {
return new Oauth2AuthenticationSuccessHandler();
}

@Bean
public AuthenticationFailureHandler oauth2AuthenticationFailureHandler(){
return new Oauth2AuthenticationFailureHandler(objectMapper);
}
}

Share