【发布时间】:2017-07-10 07:08:32
【问题描述】:
我有一个 rest api,我在其中使用 spring security 基本授权进行身份验证,客户端为每个请求发送用户名和密码。 现在,我想实现基于令牌的身份验证,当用户首先通过身份验证时,我将在响应标头中发送一个令牌。对于进一步的请求,客户端可以在标头中包含该令牌,该令牌将用于对用户进行资源身份验证。我有两个身份验证提供程序 tokenAuthenticationProvider 和 daoAuthenticationProvider
@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {
@Autowired
private TokenAuthentcationService service;
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
final HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
final String token = request.getHeader(Constants.AUTH_HEADER_NAME);
final Token tokenObj = this.service.getToken(token);
final AuthenticationToken authToken = new AuthenticationToken(tokenObj);
return authToken;
}
@Override
public boolean supports(final Class<?> authentication) {
return AuthenticationToken.class.isAssignableFrom(authentication);
}
}
在 daoAuthenticationProvider 中,我正在设置自定义 userDetailsService 并通过从数据库中获取用户登录详细信息对其进行身份验证(只要使用 Authorization:Basic bGllQXBpVXNlcjogN21wXidMQjRdTURtR04pag== 作为标头传递用户名和密码,它就可以正常工作)
但是当我使用 X-AUTH-TOKEN(即 Constants.AUTH_HEADER_NAME)在标头中包含令牌时,不会调用 tokenAuthenticationProvider。我收到错误
{"timestamp":1487626368308,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/find"}
这就是我添加身份验证提供程序的方式。
@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
final UsernamePasswordAuthenticationProvider daoProvider = new
UsernamePasswordAuthenticationProvider(this.service, this.passwordEncoder());
auth.authenticationProvider(this.tokenAuthenticationProvider);
auth.authenticationProvider(daoProvider);
}
请建议我如何在不损害 spring 安全性的当前行为的情况下实现基于令牌的身份验证。
【问题讨论】:
-
您有不同的方法可以做到这一点,您可以直接在每个过滤器上@Autowired 提供程序,或者在一个身份验证管理器中设置该提供程序,并在两个过滤器中使用它。当然,你必须在 Spring Security FilterChain 中设置这两个 Filter。
-
您已经设置了两次 authenticationProvider,第二个 daoProvider 会不会覆盖第一个 tokentAuthenticationProvider,这正是没有运行的类?
-
@ChrisZ 在下面查看我的答案。它对我有用
标签: java spring-security