【问题标题】:Where do i put check for authentication in spring UsernamePasswordAuthenticationFilter?我在哪里检查 spring UsernamePasswordAuthenticationFilter 中的身份验证?
【发布时间】:2015-06-09 22:53:43
【问题描述】:

我正在通过 json 对象从客户端应用程序传递用户名和密码,并且我正在使用 UsernamePasswordAuthenticationFilter 来验证用户身份,如问题 Spring Security and JSON Authentication 的答案 https://stackoverflow.com/a/19572145/4070142 中所建议的那样。

我的问题是我在哪里检查身份验证?我的意思是我在哪里放if(username.equals("user123")&&password.equals("password123")) {return true;}

代码请参考上述链接问题的答案https://stackoverflow.com/a/19572145/4070142

【问题讨论】:

  • 你没有。这就是 Spring Security 正在为您做的事情,
  • 是的,没错,但是我们需要在配置文件中的 标签中进行配置。因此,如果我将手动有效的用户凭据放入 标记中,那么如何将其与我的自定义过滤器 标记链接?
  • 你给它一个别名,然后把它注入你的过滤器。尽管我不会寻求您在另一个线程中的解决方案。我也不会链接到该线程,但会在此处提供所有信息,让想要帮助您的人单击以获取所有信息并不是一件好事。

标签: spring spring-security


【解决方案1】:

实际的用户名和密码比较发生在身份验证提供商处。 UsernamePasswordAuthenticationFilter 获取用户名/密码并传递给 authenticationManager,后者又将其委托给 authenticationProvider。在您的情况下,您需要添加一个自定义身份验证提供程序,如下所示:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();
    if(username.equals("user123") && password.equals("password123")) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); //assign some role
        Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
        return auth; //return Authentication object, not true
    } else {
        return null;
    }
}

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

}

在我们的配置中声明新的身份验证提供程序:

<authentication-manager>
    <authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

参考:
https://danielkaes.wordpress.com/2013/02/20/custom-authentication-provider-in-spring/

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2015-03-12
    • 2018-04-04
    • 2021-07-19
    • 1970-01-01
    • 2014-08-15
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多