如何解码令牌并分配为字符串以匹配对象?
示例:用户使用电话号码登录,它将在解码时生成一个 jwt 令牌,这将是:
{
"sub": "+440000010010" //can be any phone number
}
然后我需要获取此电话号码并与匹配字段 phoneNumber 进行比较,然后它将生成有效的身份验证。
我的代码错误显示为不兼容的类型 java.lang.string
我的令牌句柄生成并验证令牌
public String generate(String username) {
Claims claims = Jwts.claims().setSubject(username);
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
return Jwts.builder()
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public JwtUserDetails validate (String token) {
JwtUserDetails jwtUserDetails = null;
try {
Claims body = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
jwtUserDetails = new JwtUserDetails(body.getSubject(), token);
} catch (Exception e) {
e.printStackTrace();
}
return jwtUserDetails;
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
return true;
} catch (SignatureException ex) {
logger.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
logger.error("Invalid JWT token");
} catch (ExpiredJwtException ex) {
logger.error("Expired JWT token");
} catch (UnsupportedJwtException ex) {
logger.error("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
logger.error("JWT claims string is empty.");
}
return false;
}
我的过滤器是
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && jwtTokenHandler.validateToken(jwt)) {
String phoneNumber = jwtTokenHandler.validate(jwt) ;
UserDetails userDetails = customUserDetailsService.loadUserPhone(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
我的整个代码是在我测试时生成并验证令牌但是当我尝试匹配这些值时给出这个错误,有人知道吗?我仍然需要java spring。