我正在尝试使用以下方法来保护我的 REST 服务器JWT
我已经实现了自己的(这意味着 JWT 中没有 spring 的东西可以自行处理,其他一切都是Spring
当然)。
我有这门课:JWTToken implements Authentication
.
我有一个过滤器负责设置JWTToken
实例位于SecurityContextHolder
:
public class JwtFilter extends GenericFilterBean {
public void doFilter(...) {
....
JWTToken token = new JWTToken(jwt); // this init the Authentication object with all the jwt claims
SecurityContextHolder.getContext().setAuthentication(token);
....
}
我还有一个用于调试此问题的资源:
@RequestMapping(
value = "/protected_resource",
method = RequestMethod.POST
)
@RolesAllowed("admin")
public RESTResponse<String> debugJwt() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // here I can see that the context is the right one
return new RESTResponse<>("This was successful", "feedback message", true);
}
我错过了一个谜题,我在任何在线资源中都找不到这个谜题,这就是如何实现WebSecurityConfigurerAdapter
特别是configure(HttpSecurity http)
metohd.
当我尝试这样做时,例如:
http.authorizeRequests().anyRequest().authenticated()
请求没有通过此,并且资源没有被调用。
我在这里缺少什么?
Your JWTToken
类应该实现该方法:
Collection<? extends GrantedAuthority> getAuthorities();
该实现应该返回用户授予的角色的集合,其中之一是“admin”角色,如下所示:
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(new SimpleGrantedAuthority("admin"));
}
当然,在您的情况下,您将查询数据库或 JWT 令牌并解析用户角色。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)