如何从 JWT 令牌身份验证中获取声明值

我已经在令牌提供者的 JWT 令牌中设置了声明。现在我想在 API 被命中时通过身份验证获得声明价值。


我已经检查了委托人、详细信息、凭证、权限,但我没有收到任何索赔。


Claims claims = Jwts.claims().setSubject(authentication.getName());

    claims.put(AUTHORITIES_KEY, authorities);

    claims.put("userId", userRepo.findUserIdByUsername(authentication.getName()));


   return Jwts.builder()

            .setSubject(authentication.getName())

            .setClaims(claims)

            //.claim(AUTHORITIES_KEY, authorities)

            .signWith(SignatureAlgorithm.HS512, SIGNING_KEY)

            .setIssuedAt(new Date(System.currentTimeMillis()))

            .setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000))

            .compact();

我想从身份验证中获取“userId”声明或从令牌中获取声明值的任何其他方式。


繁华开满天机
浏览 277回答 1
1回答

蝴蝶不菲

这就是我从令牌中读取声明的方式private Claims getAllClaimsFromToken(String token) {&nbsp; &nbsp; &nbsp; &nbsp; Claims claims;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; claims = Jwts.parser()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .setSigningKey(SECRET)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .parseClaimsJws(token)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getBody();&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LOGGER.error("Could not get all claims Token from passed token");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; claims = null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return claims;&nbsp; &nbsp; }我将它用于 JWT<dependency>&nbsp; &nbsp; <groupId>io.jsonwebtoken</groupId>&nbsp; &nbsp; <artifactId>jjwt</artifactId>&nbsp; &nbsp; <version>0.9.0</version></dependency>编辑1:添加过滤器以从请求和验证中获取令牌import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.web.filter.OncePerRequestFilter;public class TokenAuthenticationFilter extends OncePerRequestFilter {&nbsp; &nbsp; protected final Log logger = LogFactory.getLog(getClass());&nbsp; &nbsp; private TokenHelper tokenHelper;&nbsp; &nbsp; private UserDetailsService userDetailsService;&nbsp; &nbsp; public TokenAuthenticationFilter(TokenHelper tokenHelper, UserDetailsService userDetailsService) {&nbsp; &nbsp; &nbsp; &nbsp; this.tokenHelper = tokenHelper;&nbsp; &nbsp; &nbsp; &nbsp; this.userDetailsService = userDetailsService;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void doFilterInternal(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpServletRequest request,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpServletResponse response,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FilterChain chain&nbsp; &nbsp; ) throws IOException, ServletException {&nbsp; &nbsp; &nbsp; &nbsp; String username;&nbsp; &nbsp; &nbsp; &nbsp; String authToken = tokenHelper.getToken(request);&nbsp; &nbsp; &nbsp; &nbsp; logger.info("AuthToken: "+authToken);&nbsp; &nbsp; &nbsp; &nbsp; if (authToken != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // get username from token&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username = tokenHelper.getUsernameFromToken(authToken);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logger.info("UserName: "+username);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (username != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // get user&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UserDetails userDetails = userDetailsService.loadUserByUsername(username);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (tokenHelper.validateToken(authToken, userDetails)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // create authentication&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; authentication.setToken(authToken);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecurityContextHolder.getContext().setAuthentication(authentication);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logger.error("Something is wrong with Token.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; chain.doFilter(request, response);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java