我正在查看此项目(https://github.com/szerhusenBC/jwt-spring-security-demo)以了解如何使用JWT身份验证。我想实施访客身份验证带和不带凭据(这些用户不在数据库中)。我修改了 JwtAuthenticationFilter 类以支持 AnonymousAuthentication ,但是如果我不在请求中发送正文,则会出现错误的请求错误。我想修改此项目以获取令牌而不向服务器发送用户名和密码凭据。有可能做到吗?或者我可以建立一个来宾帐户?我能提一下吗?
...
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse resp,
FilterChain chain)
throws ServletException, IOException {
String token = req.getHeader(this.tokenHeader);
String username = tokenUtil.getUsernameFromToken(token);
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null)
{
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (tokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
else
{
AnonymousAuthenticationToken authguest = new AnonymousAuthenticationToken("anonymous","anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
authguest.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
SecurityContextHolder.getContext().setAuthentication(authguest);
}
chain.doFilter(req, resp);
}
...