我有一个弹簧数据休息微服务,有以下实体
用户有笔记本电脑列表,每个笔记本电脑都有自己的规格。现在重点是,用户可以通过另一个微服务登录,并获得JWT。然后,他为自己创建了一台笔记本电脑,并为笔记本电脑添加了技术规格。
以下是将规格添加到笔记本电脑的要求
curl -i -X PUT http://localhost:8080/laptop/1/specs -H "Content-Type:text/uri-list" -d "http://localhost:8080/specs/1"
我可以在安全过滤器中从JWT获取用户的ID,因此如何验证资源"属于"对用户?如何确保用户不更新其他用户的笔记本电脑规格?这只是展示,实际上模型的数量大约为30,那么是否有动态解决方案来验证用户/资源关联?
这是我的安全过滤器的代码
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = JWTAuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}
JWT验证器
public static Authentication getAuthentication(HttpServletRequest request) {
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
String authToken = authHeader != null ? authHeader.replace(TOKEN_PREFIX, "") : null;
if (authToken != null) {
Claims claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(authToken)
.getBody();
String username = claims.getSubject();
@SuppressWarnings("unchecked") final List<String> authoritiesClaim = (List<String>) claims.get(AUTHORITIES);
final List<SimpleGrantedAuthority> authorities = authoritiesClaim
.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return username != null ?
new UsernamePasswordAuthenticationToken(username, null, authorities) :
null;
}
return null;
}
和网络安全配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}