Spring Security -自定义异常TranslationFilter

mwg9r5ms  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(502)

这个问题实际上与这个问题有关。
根据@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());
    }
}

customauthenticationprovider

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

}

customexceptiontranslationfilter

@Component
public class CustomExceptionTranslationFilter extends ExceptionTranslationFilter {

    public CustomExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationEntryPoint);
    }
}

自定义AuthenticationEntryPoint

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

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

p/s:很抱歉问了一个基本的问题,我对spring&spring security很陌生。

nnvyjq4y

nnvyjq4y1#

设计意图 AuthenticationEntryPoint 启动/启动身份验证。但是,您的实现 CustomAuthenticationEntryPoint 不会这样做。相反,它只是发回一个未经授权的响应。请参阅javadoc for authenticationentrypoint以获取有关实现细节的更多详细信息。
根据您的配置,您正在使用http basic进行身份验证:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .httpBasic();
}

此特定配置将自动配置 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());
}

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

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

你实施的 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);
    }
}

authenticationfailurehandler专门设计用于处理失败的身份验证尝试。

相关问题