无法在令牌头中设置JWT令牌类型。
这是为了制作我已经在JAX-RS中开发的安全API。基本上,我已经通过Jwts.builder()方法生成了一个令牌,作为回报,我在APPLICATION_JSON中获得了令牌,然后我将此令牌粘贴到了https://jwt.io/调试器中。所以我知道没有指定令牌头的令牌类型,只有{ “ alg”:“ HS512” } 也许这可能是我无法访问安全API的原因。当我尝试访问安全的API时,出现“不支持签名声明JWS”异常。
AuthenticationService.java
private String issueToken(String login, String password) {
LocalDateTime now = LocalDateTime.now().plusMinutes(10L);
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date jwtExpiry = Date.from(instant);
String jwtToken = Jwts.builder().setSubject(login).setIssuer("XYZ").setIssuedAt(new Date())
.setExpiration(jwtExpiry).signWith(SignatureAlgorithm.HS512, "secretKey").compact();
return jwtToken;
}
public class JWTTokenNeededFilter implements ContainerRequestFilter
{
public static final Logger logger = Logger.getLogger(JWTTokenNeededFilter.class);
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String token = requestContext.getHeaderString("userToken");
if (token == null) {
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
try {
Jwts.parser().setSigningKey("secretKey").parseClaimsJwt(token);
logger.info("Valid Token " + token);
} catch (ExpiredJwtException expiredJwtException) {
logger.info("Token Expires " + expiredJwtException);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
catch (Exception exception) {
logger.info("Exceptioin " + exception);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}
我期望这样的令牌头
{ “ alg”:“ HS512”, “ typ”:“ JWT” }
答案 0 :(得分:1)
您可以按照以下说明使用标头进行设置:https://github.com/jwtk/jjwt/issues/174
Header header = Jwts.header();
header.setType("JWT");
然后将标题设置为builder(我尚未编译代码)
private String issueToken(String login, String password) {
LocalDateTime now = LocalDateTime.now().plusMinutes(10L);
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date jwtExpiry = Date.from(instant);
Header header = Jwts.header();
header.setType("JWT");
String jwtToken =
Jwts.builder().setHeader((Map<String, Object>)
header).setSubject(login).setIssuer("XYZ").setIssuedAt(new
Date())
.setExpiration(jwtExpiry).signWith(SignatureAlgorithm.HS512,
"secretKey").compact();
return jwtToken;
}
答案 1 :(得分:1)
您可以仅使用setHeaderParam("typ","JWT")
jwt构建器方法来设置标题。
https://github.com/jwtk/jjwt#header-parameters
String token = Jwts.builder()
.setHeaderParam("typ","JWT")
.setSubject(user.getUserId().toString())
.claim("Roles",authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
.signWith(Keys.hmacShaKeyFor(key))
.compact();