首页 文章

Spring Boot / Spring安全性AuthenticationEntryPoint未执行

提问于
浏览
9

我有一个创建了一个包含这个方法的类JwtAuthenticationFilter:

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    Authentication authentication = null;

    if(hasJsonToken(request)) {
        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(getJsonToken(request)); 
        authentication = getAuthenticationManager().authenticate(jwtAuthenticationToken);           
    } else {
        throw new AuthenticationCredentialsNotFoundException(AUTHENTICATION_CREDENTIALS_NOT_FOUND_MSG);
    }

    return authentication;
}

如果未提供JWT,则抛出AuthenticationCredentialsNotFoundException . 我希望这会在我的AuthenticationEntryPoint中触发begin方法 - 看起来像这样:

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {   
response.sendError(HttpStatus.UNAUTHORIZED.value(),HttpStatus.UNAUTHORIZED.getReasonPhrase());
}

开始方法没有被调用 . 这在我的spring安全配置(或其中的一部分)中:

@Bean
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
    return new RestAuthenticationEntryPoint();              
}

protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint()).and()
        .csrf().disable()
        .authorizeRequests().antMatchers(AUTHORISED_SERVICE_REQUESTS_ANT_MATCHER).authenticated()
        .anyRequest().permitAll();      
}

我不确定这里有什么错误,我希望有人指出我 . 谢谢

我的SecurityConfig类扩展了WebSecurityConfigurerAdapter,并使用@Configuration和@EnableWebSecurity进行了注释 .

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
}

我正在使用 spring 靴 .

所以...最终我通过创建自定义AuthenticationFailureHandler并在我的Authentication F.ilter中注册它来获得我想要的行为

jwtAuthenticationFilter.setAuthenticationFailureHandler(new JwtAuthenticationFailureHandler());

我现在的问题是,这是正确的做法,AuthenticationEntryPoint和AuthenticationFailureHandler有什么区别?

1 回答

  • 0

    AuthenticationEntryPointAuthenticationFailureHandler 之间的区别在于前者用于"tell"未经身份验证的用户进行身份验证,例如,通过将其重定向到登录表单 . 后者用于处理错误的登录尝试 .

    你的 AuthenticationEntryPoint 很可能没有被调用,因为你扔了任何东西 . 在没有凭证的情况下,它需要抛出异常 .

    如果您想要将用户重定向到任何地方,那么您可以使用 org.springframework.security.web.authentication.HttpStatusEntryPoint 或像您这样的入口点来返回状态代码 .

相关问题