【发布时间】:2018-02-24 20:37:42
【问题描述】:
我在应用程序中有两个级别的访问权限:所有人和仅授权。
我以注册用户身份登录, 但如果我尝试请求受保护的数据,则会收到错误消息:
身份验证失败:找不到 AuthenticationProvider com.company.security.tokenAuth.TokenAuthentication
我的TokenAuthentication班级:
public class TokenAuthentication extends AbstractAuthenticationToken {
private static final long serialVersionUID = -4021530026682433724L;
private UserDetails principal;
private String token;
public TokenAuthentication(String token) {
super(new HashSet<>());
this.token = token;
}
public TokenAuthentication(String token, Collection<? extends GrantedAuthority> authorities,
boolean isAuthenticated, UserDetails principal) {
super(authorities);
this.principal = principal;
this.setAuthenticated(isAuthenticated);
}
@Override
public Object getCredentials() {
return null;
}
@Override
public UserDetails getPrincipal() {
return principal;
}
public String getToken() {
return token;
}
}
我的TokenAuthenticationProvider班级:
@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {
private TokenService tokenService;
private AccountDetailsService accountService;
public TokenAuthenticationProvider(TokenService tokenService, AccountDetailsService accountService) {
this.tokenService = tokenService;
this.accountService = accountService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication instanceof TokenAuthentication) {
return processAuthentication((TokenAuthentication) authentication);
} else {
authentication.setAuthenticated(false);
return authentication;
}
}
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(TokenAuthentication.class);
}
private TokenAuthentication processAuthentication(TokenAuthentication authentication) {
try {
Account token = tokenService.parseToken(authentication.getToken());
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority(token.getRole().name()));
return new TokenAuthentication(authentication.getToken(), authorities,
true, new AccountDetails((Account) accountService.loadUserByUsername(token.getEmail())));
} catch (ValidationException e) {
throw new AuthenticationServiceException("Invalid token");
} catch (Exception e) {
throw new AuthenticationServiceException("Token corrupted");
}
}
}
我的问题是什么? 感谢您的帮助。
【问题讨论】:
-
可能是我的配置有问题。因为如果你运行代码并通过招摇检查它可以工作。
标签: spring-mvc spring-boot spring-security jwt