accessDeniedHandler metodu
Hatalı kullanıcı adı, şifresi gönderilmişse çağrılır.
Hatalı kullanıcı adı, şifresi gönderilmişse çağrılır.
Örnek
Elimizde şöyle bir kod olsun.
Örnek
Şöyle yaparız.
Şöyle yaparız.
Doğrulanmamış kullanıcıyı ana sayfaya yönlendirir.
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
  @Override
  public void onAuthenticationFailure(HttpServletRequest request,
                                      HttpServletResponse response,
      AuthenticationException ex) throws IOException, ServletException {
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    ...
  }
}@Configuration
@EnableWebSecurity
@ComponentScan("your.base.package")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}
  @Bean
  public AccessDeniedHandler accessDeniedHandler() {
    return new CustomAuthenticationFailureHandler();
  }
}Örnek
Şöyle yaparız.
httpSecurity.exceptionHandling().accessDeniedPage("/login?accessDenied");  Şöyle yaparız.
HttpSecurity http = ...;
http
  ...
  .and()
  .exceptionHandling().accessDeniedPage("/errors/error403")
  .and()
  ...Doğrulanmamış kullanıcıyı ana sayfaya yönlendirir.
REST için kullanıyorsak başka sayfaya yönlendirmeye gerek yok, sadece HTTP 401 Unauthorized gönderilir.
Örnek
Şöyle yaparız. AuthenticationEntryPoint nesnesi geçilir.
http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());Şöyle yaparızz
.exceptionHandling()
  .accessDeniedHandler((request, response, accessDeniedException) -> {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
      objectMapper.writeValue(
        response.getWriter(),
        ErrorResponseBody
          .builder()
          .code(ErrorType.ACCESS_DENIED)
          .status(HttpServletResponse.SC_FORBIDDEN)
          .message("Access denied")
          .build()
      );
    })
    .authenticationEntryPoint((request, response, authException) -> {
      response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        objectMapper.writeValue(
          response.getWriter(),
            ErrorResponseBody
              .builder()
              .code(ErrorType.LOGIN_REQUIRED)
              .status(HttpServletResponse.SC_UNAUTHORIZED)
              .message("You are not authorized to access this resource")
              .build()
            );
    })