简体   繁体   English

Spring Boot Security:使用自定义身份验证筛选器进行异常处理

[英]Spring Boot Security: Exception handling with custom authentication filters

I'm using Spring Boot + Spring Security (java config). 我正在使用Spring Boot + Spring Security(java配置)。 My question is the old one, but all info which I've found is partially outdated and mostly contains xml-config (which difficult or even impossible to adapt some time) 我的问题是旧问题,但我发现的所有信息都已过时且大部分都包含xml-config(很难甚至无法适应一段时间)

I'm trying to do stateless authentication with a token (which doesn't stored on server side). 我正在尝试使用令牌(不存储在服务器端)进行无状态身份验证。 Long story short - it is a simple analogue for JSON Web Tokens authentication format. 长话短说 - 它是JSON Web Tokens认证格式的简单模拟。 I'm using two custom filters before default one: 我在默认过滤器之前使用两个自定义过滤器:

  • TokenizedUsernamePasswordAuthenticationFilter which creates token after successful authentication on entry point ("/myApp/login") TokenizedUsernamePasswordAuthenticationFilter,在入口点成功验证后创建令牌(“/ myApp / login”)

  • TokenAuthenticationFilter which tries to authenticate the user using token (if provided) for all restricted URLs. TokenAuthenticationFilter尝试使用令牌(如果提供)对所有受限制的URL进行身份验证。

I do not understand how properly handle custom exceptions(with custom message or redirect) if I want some... Exceptions in filters are not relevant to exceptions in controllers, so they will not be handled by same handlers... 如果我想要一些,我不明白如何正确处理自定义异常(使用自定义消息或重定向)...过滤器中的异常与控制器中的异常无关,因此它们不会由相同的处理程序处理...

If I've understood right, I can not use 如果我理解得对,我就不能用

.formLogin()

                .defaultSuccessUrl("...")
                .failureUrl("...")
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAthenticationFailureHandler)

to customize exceptions, because I use custom filters... So what the way to do it? 自定义异常,因为我使用自定义过滤器......那么这样做的方法是什么?

My config: 我的配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()  .anonymous()

        .and()  .authorizeRequests()                      
                .antMatchers("/").permitAll()
                ...
                .antMatchers(HttpMethod.POST, "/login").permitAll()                    
        .and()                    
                .addFilterBefore(new TokenizedUsernamePasswordAuthenticationFilter("/login",...), UsernamePasswordAuthenticationFilter.class)                      
                .addFilterBefore(new TokenAuthenticationFilter(...), UsernamePasswordAuthenticationFilter.class)

    }

We can set AuthenticationSuccessHandler and AuthenticationFailureHandler in your custom filter as well. 我们也可以在自定义过滤器中设置AuthenticationSuccessHandler和AuthenticationFailureHandler。

Well in your case, 那么在你的情况下,

// Constructor of TokenizedUsernamePasswordAuthenticationFilter class
public TokenizedUsernamePasswordAuthenticationFilter(String path, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
    setAuthenticationSuccessHandler(successHandler);
    setAuthenticationFailureHandler(failureHandler);
}

Now to use these handlers just invoke onAuthenticationSuccess() or onAuthenticationFailure() methods. 现在使用这些处理程序只需调用onAuthenticationSuccess()onAuthenticationFailure()方法。

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                          FilterChain chain, Authentication authentication) throws IOException, ServletException {

    getSuccessHandler().onAuthenticationSuccess(request, response, authentication);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            AuthenticationException failed)
          throws IOException, ServletException {

    getFailureHandler().onAuthenticationFailure(request, response, failed);
}

You can create your custom authentication handler classes to handle the success or failure cases. 您可以创建自定义身份验证处理程序类来处理成功或失败案例。 For example, 例如,

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse,
                                      Authentication authentication)
          throws IOException, ServletException {

    SecurityContextHolder.getContext().setAuthentication(authentication);
    // Do your stuff, eg. Set token in response header, etc.
  }
}

Now for handling the exception, 现在处理异常,

public class LoginFailureHandler implements AuthenticationFailureHandler {

  @Override
  public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse,
                                      AuthenticationException e)
          throws IOException, ServletException {

    String errorMessage = ExceptionUtils.getMessage(e);

    sendError(httpServletResponse, HttpServletResponse.SC_UNAUTHORIZED, errorMessage, e);
  }


  private void sendError(HttpServletResponse response, int code, String message, Exception e) throws IOException {
    SecurityContextHolder.clearContext();

    Response<String> exceptionResponse =
            new Response<>(Response.STATUES_FAILURE, message, ExceptionUtils.getStackTrace(e));

    exceptionResponse.send(response, code);
  }
}

My custom response class to generate desired JSON response, 我的自定义响应类,用于生成所需的JSON响应,

public class Response<T> {

  public static final String STATUES_SUCCESS = "success";
  public static final String STATUES_FAILURE = "failure";

  private String status;
  private String message;
  private T data;

  private static final Logger logger = Logger.getLogger(Response.class);

  public Response(String status, String message, T data) {
    this.status = status;
    this.message = message;
    this.data = data;
  }

  public String getStatus() {
    return status;
  }

  public String getMessage() {
    return message;
  }

  public T getData() {
    return data;
  }

  public String toJson() throws JsonProcessingException {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
      return ow.writeValueAsString(this);
    } catch (JsonProcessingException e) {
      logger.error(e.getLocalizedMessage());
      throw e;
    }
  }

  public void send(HttpServletResponse response, int code) throws IOException {
    response.setStatus(code);
    response.setContentType("application/json");
    String errorMessage;

    errorMessage = toJson();

    response.getWriter().println(errorMessage);
    response.getWriter().flush();
  }
}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM