Spring 安全 - 自定义 ExceptionTranslationFilter

lxn*_*xnx 3 java spring spring-mvc spring-security

这个问题其实是和这个issue相关的问题

根据@harsh-poddar 的建议,我相应地添加了过滤器。

但是,在添加之后,即使使用有效凭据,我似乎也无法登录。

以下是相关代码:

安全配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//  @Bean
//  public CustomAuthenticationEntryPoint customAuthenticationEntryPoint() {
//      return new CustomAuthenticationEntryPoint();
//  }

@Bean
public CustomExceptionTranslationFilter customExceptionTranslationFilter() {
    return new CustomExceptionTranslationFilter(new CustomAuthenticationEntryPoint());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        //Note : Able to login without this filter, but after adding this, valid credential also fails
        .addFilterAfter(customExceptionTranslationFilter(), ExceptionTranslationFilter.class)
//      .exceptionHandling()
//          .authenticationEntryPoint(new customAuthenticationEntryPoint())
//          .and()
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .requestCache()
            .requestCache(new NullRequestCache())
            .and()
        .httpBasic()
            .and()
        .csrf().disable();
}

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthenticationProvider());
    }
}
Run Code Online (Sandbox Code Playgroud)

自定义身份验证提供程序

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

public CustomAuthenticationProvider() {
    super();
}

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException  {
    final String name = authentication.getName();
    final String password = authentication.getCredentials().toString();
    if (name.equals("admin") && password.equals("password")) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        final UserDetails principal = new User(name, password, grantedAuths);
        final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
        return auth;
    } else {
        throw new BadCredentialsException("NOT_AUTHORIZED");
    }
}

    @Override
    public boolean supports(final Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
Run Code Online (Sandbox Code Playgroud)

自定义异常翻译过滤器

@Component
public class CustomExceptionTranslationFilter extends ExceptionTranslationFilter {

    public CustomExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationEntryPoint);
    }
}
Run Code Online (Sandbox Code Playgroud)

自定义身份验证入口点

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized.");
    }
}
Run Code Online (Sandbox Code Playgroud)

p/s :对于基本问题,我很抱歉,我是 spring 和 spring 安全方面的新手。

小智 5

预期的设计AuthenticationEntryPoint是启动/启动身份验证。但是,您的实现CustomAuthenticationEntryPoint不会这样做。相反,它只是发回未经授权的响应。有关实现细节的更多详细信息,请参阅AuthenticationEntryPoint 的javadoc 。

根据您的配置,您使用 HTTP Basic 进行身份验证:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .httpBasic();
}
Run Code Online (Sandbox Code Playgroud)

此特定配置将自动配置BasicAuthenticationEntryPoint哪个是AuthenticationEntryPoint. 根据服务器协议BasicAuthenticationEntryPoint将使用 http 响应头挑战用户WWW-Authenticate: Basic realm="User Realm"进行身份验证。

但是,事实上您正在配置自己的CustomAuthenticationEntryPoint它最终会覆盖BasicAuthenticationEntryPoint这不是您想要做的。

其他岗位推荐的配置而这又是不是你想要做什么。

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .httpBasic()
            .and()
        .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
}
Run Code Online (Sandbox Code Playgroud)

如果您的主要目标是在身份验证失败时向用户提供自定义响应,那么我会建议使用已配置的AuthenticationFailureHandler. 这是配置:

http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin().failureHandler(new DefaultAuthenticationFailureHandler())
        .and()
    .csrf().disable();   // NOTE: I would recommend enabling CSRF
Run Code Online (Sandbox Code Playgroud)

您的实现DefaultAuthenticationFailureHandler将是:

public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // Set status only OR do whatever you want to the response
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
}
Run Code Online (Sandbox Code Playgroud)

AuthenticationFailureHandler是专门用来处理认证尝试失败。