我在应用程序中有两个级别的访问权限:适用于所有人,仅适用于授权。
我以注册用户身份登录, 但如果我尝试请求受保护的数据,我会收到错误:
身份验证失败:找不到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");
}
}
}
我的问题是什么? 谢谢你的帮助。
答案 0 :(得分:0)
我找到了答案。 我根据项目参考https://github.com/oharsta/spring-jwt/tree/50f130ee5d63d746cc9d7adf2f0d8f085327a84a更改了我的身份验证 并且固定角色,因为我只有一个用户和一个enum形式的角色。在身份验证期间,使用角色列表。 解决了这个问题后,一切正常。