ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-Spring Boot Security:使用自定义身份验证过滤器的异常处理

2019-11-19 09:01:26  阅读:487  来源: 互联网

标签:spring-boot spring-security java spring-mvc


我正在使用Spring Boot Spring Security(java config).
我的问题是旧的,但是我发现的所有信息都已部分过时,并且大部分包含xml-config(很难或什至不可能适应一段时间)

我正在尝试使用令牌(不存储在服务器端)进行无状态身份验证.长话短说-这是JSON Web令牌认证格式的简单模拟.
我在默认一个之前使用了两个自定义过滤器:

> TokenizedUsernamePasswordAuthenticationFilter,它在之后创建令牌
在入口点(“ / myApp /登录”)成功认证
> TokenAuthenticationFilter,它尝试使用令牌(如果提供)对所有受限URL进行身份验证.

我不了解如果我想要一些如何正确处理自定义异常(带有自定义消息或重定向).
过滤器中的异常与控制器中的异常无关,因此它们不会由相同的处理程序处理…

如果我理解正确,则无法使用

.formLogin()

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

自定义例外,因为我使用自定义过滤器…
那怎么办呢?

我的配置:

@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)

    }

解决方法:

我们也可以在您的自定义过滤器中设置AuthenticationSuccessHandler和AuthenticationFailureHandler.

好吧,你的情况

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

现在要使用这些处理程序,只需调用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);
}

您可以创建自定义身份验证处理程序类来处理成功或失败案例.例如,

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.
  }
}

现在要处理异常,

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);
  }
}

我的自定义响应类,用于生成所需的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();
  }
}

我希望这有帮助.

标签:spring-boot,spring-security,java,spring-mvc
来源: https://codeday.me/bug/20191119/2034960.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有