【问题标题】:Spring security baisc authentication only validating first requestSpring security基本身份验证仅验证第一个请求
【发布时间】:2018-07-19 16:17:12
【问题描述】:

我正在使用带有自定义身份验证提供程序的 spring 基本身份验证:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomAuthenticationProvider authProvider;

@Override
protected void configure(
        AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(authProvider);
}

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

    @Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    if (customauth()) { // use the credentials
        // and authenticate against the third-party system
        {
            return new UsernamePasswordAuthenticationToken(
                    name, password, new ArrayList<>());
        }
    } else {
        return null;
    }

}

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

为了测试这一点,我使用邮递员进行以下测试:

无效凭据 -> 401 未经授权

正确的凭据 -> 200 OK

无效的凭据 -> 200 OK

我的问题是最后一个请求应该返回 401 未经授权,并且成功登录后的每个后续请求都是 200 OK 即使使用错误的令牌和没有令牌。

提前致谢。

【问题讨论】:

  • 您的 customauth() 方法中有什么?您可以尝试查看此示例:github.com/eugenp/tutorials/tree/master/…,如果您有省略某些内容,请尝试与您的代码进行比较。现在我唯一看到的是你没有 authenticationEntryPoint 但我不知道它是否真的需要但你可以尝试:.httpBasic() .authenticationEntryPoint(authenticationEntryPoint);

标签: java spring spring-security


【解决方案1】:

当你登录成功后,Spring Security 将创建一个Authentication 对象,并将其放入你的HTTP 会话中的SecurityContext。只要您在服务器上有一个有效的会话与有效的Authentication 对象,Spring Security 将不会再次验证您的请求,并将使用保存在会话中的Authentication 对象。

【讨论】:

    【解决方案2】:

    这是一个 Spring Security 特性,见SEC-53:

    检查 SecurityContextHolder 以获得经过身份验证的身份验证并在这种情况下重用它,不要再次调用身份验证管理器。

    如果你想重新认证,你可以

    • 根本不使用任何会话
    • 在重新验证之前注销

    在这两种情况下,Spring Security 都不会找到保存在会话中的经过身份验证的用户,并将使用新的用户名和密码进行身份验证。

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 2016-03-20
      • 1970-01-01
      • 2016-04-30
      • 2013-01-11
      • 2015-07-22
      • 2017-09-14
      • 2012-08-15
      • 2013-05-13
      相关资源
      最近更新 更多