[英]Secure REST Api with Spring boot and JWT
我正在尝试使用JWT
来保护我的REST服务器,我已经实现了自己(意味着JWT中没有任何弹簧处理它自己,其他一切都是Spring
当然)。
我有这个类: JWTToken implements Authentication
。
我有一个过滤器,负责在SecurityContextHolder
上设置JWTToken
实例:
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)
。
当我尝试这样做时,例如:
http.authorizeRequests().anyRequest().authenticated()
请求没有通过这个,资源没有被调用。
我在这里错过了什么?
您的JWTToken
类应该实现该方法:
Collection<? extends GrantedAuthority> getAuthorities();
实现应该返回用户授予角色的集合,其中一个将是“admin”角色,类似于:
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(new SimpleGrantedAuthority("admin"));
}
当然,在您的情况下,您将查询DB或JWT令牌并解析用户角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.