下面列出了io.jsonwebtoken.MalformedJwtException#io.jsonwebtoken.Jwts 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Gets an access token JWT for testing that is always the same.
*/
public static String getTestAccessToken() {
if (TEST_ACCESS_TOKEN != null) {
return TEST_ACCESS_TOKEN;
}
final Map<String, Object> claims = new HashMap<>();
claims.put("typ", "access");
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(Date.from(Instant.now().minus(Duration.ofHours(1))))
.setSubject("uniqueUserID")
.setExpiration(new Date(((Calendar.getInstance().getTimeInMillis() + (5 * 60 * 1000)))))
.signWith(
SignatureAlgorithm.HS256,
"abcdefghijklmnopqrstuvwxyz1234567890".getBytes(StandardCharsets.UTF_8))
.compact();
}
@GetMapping("/")
public String home(
@RequestParam(defaultValue = "test") String user,
@RequestParam(defaultValue = "LOW") String level
) throws URISyntaxException {
AuthnContext authnContext = AuthnContext.valueOf(level);
String jwtToken = Jwts.builder()
.setSubject(user)
.claim("AuthnContext", authnContext.name())
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
HttpHeaders headers = new HttpHeaders();
headers.set(JwtAuthorizationHeaderFilter.JWT_HEADER_NAME, jwtToken);
log.debug("JWT: " + jwtToken);
RequestEntity<Object> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8080/rest"));
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
return "Got: " + responseEntity.getBody();
//some idea for propagating it over thread :https://stackoverflow.com/questions/46729203/propagate-http-header-jwt-token-over-services-using-spring-rest-template
}
public static RequestUserDTO getConnUser(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token == null) {
token = getTokenFromCookis(request);
}
if (token != null) {
// 解析 Token
Claims claims = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token).getBody();
return new RequestUserDTO(
claims.get("DomainId", String.class),
claims.get("UserId", String.class),
claims.get("OrgUnitId", String.class));
}
return new RequestUserDTO();
}
@Test
public void testSerializeSecretKey() {
SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);
String token = Jwts.builder()
.setSubject(SUBJECT)
.signWith(secretKey)
.compact();
@SuppressWarnings("unchecked")
Jwt<?, Claims> jwt = Jwts.parser()
.setSigningKey(AuthTokenUtils.decodeSecretKey(secretKey.getEncoded()))
.parse(token);
assertNotNull(jwt);
assertNotNull(jwt.getBody());
assertEquals(jwt.getBody().getSubject(), SUBJECT);
}
/**
* @param jwt, JWT issued by daming.
* @return claims that contains verified mobile and scope.
* @see #verify(String, String)
*/
@Deprecated
public SmsVerificationClaims verify(String jwt) {
if (jwt == null) {
throw new BadSmsVerificationJwtException("The jwt must not be null");
}
try {
JwtParser parser = Jwts.parser()
.setSigningKey(publicKey);
if (clock != null) {
parser = parser.setClock(clock);
}
Jws<Claims> claims = parser
.parseClaimsJws(jwt);
String mobile = claims.getBody().get("mobile", String.class);
String scope = claims.getBody().get("scope", String.class);
return new SmsVerificationClaims(mobile, scope);
} catch (Exception err) {
throw new BadSmsVerificationJwtException(err.getMessage(), err);
}
}
@Test
void testAuthenticateSubIss() throws Exception {
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getClass().getResourceAsStream("/keystore.jks"), passphrase);
final Key privateKey = ks.getKey("trellis-ec", passphrase);
final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, "trellis-ec")
.setSubject("acoburn").setIssuer("http://localhost")
.signWith(privateKey, SignatureAlgorithm.ES256).compact();
final Authenticator authenticator = new FederatedJwtAuthenticator(ks,
singletonList("trellis-ec"));
final Principal p = authenticator.authenticate(token);
assertNotNull(p, "Missing principal!");
assertEquals("http://localhost/acoburn", p.getName(), "Incorrect webid!");
}
/**
* 功能描述: 生成JWT TOKEN
*
* @param employeeDTO
* @return
* @auther yandanyang
* @date 2018/9/12 0012 上午 10:08
*/
public String generateToken(EmployeeDTO employeeDTO) {
Long id = employeeDTO.getId();
/**将token设置为jwt格式*/
String baseToken = UUID.randomUUID().toString();
LocalDateTime localDateTimeNow = LocalDateTime.now();
LocalDateTime localDateTimeExpire = localDateTimeNow.plusSeconds(EXPIRE_SECONDS);
Date from = Date.from(localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant());
Date expire = Date.from(localDateTimeExpire.atZone(ZoneId.systemDefault()).toInstant());
Claims jwtClaims = Jwts.claims().setSubject(baseToken);
jwtClaims.put(CLAIM_ID_KEY, id);
String compactJws = Jwts.builder().setClaims(jwtClaims).setNotBefore(from).setExpiration(expire).signWith(SignatureAlgorithm.HS512, jwtKey).compact();
EmployeeBO employeeBO = employeeService.getById(id);
RequestTokenBO tokenBO = new RequestTokenBO(employeeBO);
return compactJws;
}
/**
* Generates a JWT token containing all needed claims. These properties are taken from the specified
* JwtUserPayload object.
*
* @param payload the payload entity with which the token will be generated
* @return the JWT token
*/
public String generateToken(JwtUserPayload payload, TokenType tokenType, boolean useExpiration) {
long maxAge = tokenType.equals(TokenType.ACCESS) ? accessTokenMaxAge : refreshTokenMaxAge;
Date expiration = useExpiration && payload.getExpiration() != null ? payload.getExpiration() :
timestampService.getDate(System.currentTimeMillis() + maxAge);
JwtUserPayload generatedPayload = JwtUserPayload.newBuilder()
.withPayload(payload)
.withExpirationDate(expiration)
.withTokenType(tokenType.getId())
.buildPayload();
Map<String, Object> jwtMap = new HashMap<>();
jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, generatedPayload);
Claims claims = Jwts.claims(jwtMap);
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret())
.compact();
}
/**
* Check user`s login info, then create a jwt token returned to front end
* @param reqPerson
* @return jwt token
* @throws ServletException
*/
@PostMapping
public RespResult login(@RequestBody() ReqPerson reqPerson) throws ServletException {
// Check if username and password is null
if (reqPerson.getUsername() == "" || reqPerson.getUsername() == null
|| reqPerson.getPassword() == "" || reqPerson.getPassword() == null)
throw new ServletException("Please fill in username and password");
// Check if the username is used
if(personService.findPersonByUsername(reqPerson.getUsername()) == null
|| !reqPerson.getPassword().equals(personService.findPersonByUsername(reqPerson.getUsername()).getPassword())){
throw new ServletException("Please fill in username and password");
}
// Create Twt token
String jwtToken = Jwts.builder().setSubject(reqPerson.getUsername()).claim("roles", "member").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secretkey").compact();
RespResult result = new RespResult();
result.setStatuscode("200 OK");
result.setMessage("login success");
result.setData(jwtToken);
return result;
}
/**
* 根据JWT获取验证令牌
* @param request
* @return
*/
public static Authentication getAuthentication(HttpServletRequest request) {
// 从Header中拿到token
String token = request.getHeader(HEADER_STRING);
if (StringUtils.isEmpty(token)) token = CookiesUtil.getCookieValueByName(request, HEADER_STRING);
if (StringUtils.isEmpty(token)) return null;
// 解析 Token
Claims claims = Jwts.parser()
// 验签
.setSigningKey(SECRET)
// 去掉 Bearer
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
// 拿用户名
String user = claims.getSubject();
// 得到 权限(角色)
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
// 返回验证令牌
return user != null ?
new UsernamePasswordAuthenticationToken(user, null, authorities) :
null;
}
@Test
public void testNotProceedRequestWhenNoWorkspaceIdClaim() throws Exception {
final HttpServletRequest requestMock = getRequestMock();
final KeyPairGenerator kpg = KeyPairGenerator.getInstance(SIGNATURE_ALGORITHM);
kpg.initialize(KEY_SIZE);
final KeyPair pair = kpg.generateKeyPair();
final Claims badClaims = new DefaultClaims();
badClaims.put(Constants.USER_ID_CLAIM, SUBJECT.getUserId());
badClaims.put(Claims.ID, "84123-132-fn31");
final String token =
Jwts.builder()
.setClaims(badClaims)
.setHeader(HEADER)
.signWith(RS512, pair.getPrivate())
.compact();
when(tokenExtractorMock.getToken(any(HttpServletRequest.class))).thenReturn(token);
machineLoginFilter.doFilter(requestMock, responseMock, chainMock);
verify(tokenExtractorMock, atLeastOnce()).getToken(any(HttpServletRequest.class));
verify(responseMock)
.sendError(
401,
"Machine token authentication failed: Unable to fetch signature key pair: no workspace id present in token");
}
@Test
void testFilterNoSecCtx() {
final Key key = secretKeyFor(SignatureAlgorithm.HS512);
final String token = Jwts.builder().setSubject(WEBID1).signWith(key).compact();
final ContainerRequestContext mockCtx = mock(ContainerRequestContext.class);
when(mockCtx.getSecurityContext()).thenReturn(null);
when(mockCtx.getHeaderString(AUTHORIZATION)).thenReturn("Bearer " + token);
final OAuthFilter filter = new OAuthFilter();
filter.setAuthenticator(new JwtAuthenticator(key));
filter.filter(mockCtx);
verify(mockCtx).setSecurityContext(securityArgument.capture());
assertEquals(WEBID1, securityArgument.getValue().getUserPrincipal().getName(), "Unexpected agent IRI!");
assertEquals(OAuthFilter.SCHEME, securityArgument.getValue().getAuthenticationScheme(), "Unexpected scheme!");
assertFalse(securityArgument.getValue().isSecure(), "Unexpected secure flag!");
assertFalse(securityArgument.getValue().isUserInRole("some role"), "Unexpectedly in user role!");
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(claims.getSubject(), "",
authorities);
return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
.compact();
}
/**
* 从数据声明生成令牌
*
* @param claims 数据声明
* @return 令牌
*/
private String generateToken(Map<String, Object> claims) {
Date expirationDate = new Date(System.currentTimeMillis() + 604800L * 1000);
return Jwts.builder().setClaims(claims).setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
private static Optional<String> getJwtUser(ServletRequest req) {
String jwt = WebUtils.toHttp(req).getHeader("Authorization");
if (null != jwt && jwt.startsWith("Bearer ")) {
try {
jwt = jwt.substring(jwt.indexOf(' ') + 1);
Jws<Claims> claims = Jwts.parser().setSigningKey(ShiroJwtProvider.SIGNING_KEY).parseClaimsJws(jwt);
String user = claims.getBody().getSubject();
return Strings.hasText(user) ? Optional.of(user) : Optional.empty();
} catch (JwtException | IllegalArgumentException e) {
LOG.error("Failed validating JWT {} from {}", jwt, WebUtils.toHttp(req).getRemoteAddr());
LOG.debug("exception", e);
}
}
return Optional.empty();
}
/**
* 根据负责生成JWT的token
*/
private String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
@Override
public String parse(String token) {
try {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getSubject();
} catch (JwtException | IllegalArgumentException e) {
throw new TokenException(e);
}
}
private static String createTokenWithAudience(Key signingKey, String audienceClaim, List<String> audience) {
JwtBuilder builder = Jwts.builder()
.setSubject(SUBJECT)
.signWith(signingKey);
builder.claim(audienceClaim, audience);
return builder.compact();
}
/**
* 创建token
* @param id
* @return
*/
public static String createJWT(String id) {
//过期时间不要太长 移动端需要长时间记住用户名 让移动端本地存储 用户名 密码即可
Date exp = DateUtils.addDays(new Date(),1) ;
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(new Date())
.setSubject(id)
.setIssuer(issuer)
.signWith(key);
builder.setExpiration(exp);
//Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}
public String refreshToken(String token, String base64Security, long TTLMillis) {
String refreshedToken;
try {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
// 生成签名密钥
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
final Claims claims = parseJWT(token, base64Security);
claims.put("creatDate", new Date());
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
.setClaims(claims)
.setSubject(getUsername(token, base64Security))
.setIssuer(getIssuer(token, base64Security))
.setAudience(getAudience(token, base64Security))
.signWith(signatureAlgorithm, signingKey);
//添加Token过期时间
if (TTLMillis >= 0) {
long expMillis = nowMillis + TTLMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp).setNotBefore(now);
}
refreshedToken = builder.compact();
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
/**
* 签发JWT
*
* @param subject
* 用户名称
* @param issuer
* 签发人
* @param period
* 有效时间
* @param roles
* 访问主张-角色
* @param permissions
* 访问主张-资源
* @param algorithm
* 算法
* @return JSON WEB TOKEN
*/
public static String issueJwt(String subject, String issuer, Long period, String roles, String permissions,
SignatureAlgorithm algorithm) {
// 当前时间戳(精确到毫秒)
long currentTimeMillis = System.currentTimeMillis();
// 秘钥
byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(properties().getJwtSecretKey());
JwtBuilder jwt = Jwts.builder();
jwt.setId(UUID.randomUUID().toString());
// 用户名
jwt.setSubject(subject);
// 签发者
if (null != issuer && !"".equals(issuer))
jwt.setIssuer(issuer);
// 签发时间
jwt.setIssuedAt(new Date(currentTimeMillis));
// 有效时间
if (null != period) {
Date expiration = new Date(currentTimeMillis + period);
jwt.setExpiration(expiration);
}
// 访问主张-角色
if (null != roles && !"".equals(roles))
jwt.claim("roles", roles);
// 访问主张-权限
if (null != permissions && !"".equals(permissions))
jwt.claim("perms", permissions);
jwt.compressWith(CompressionCodecs.DEFLATE);
jwt.signWith(algorithm, secretKeyBytes);
return jwt.compact();
}
@Override
public boolean verify(String subject, String token) {
try {
return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(subject);
} catch (Exception e) {
logger.error("Verify fail:", e);
return false;
}
}
/**
* Creates a new JWT for the specified principal. Token is signed using
* the SecretKey with an HMAC 256 algorithm.
*
* @param principal the Principal to create the token for
* @param permissions the effective list of permissions for the principal
* @param identityProvider the identity provider the principal was authenticated with. If null, it will be derived from principal
* @return a String representation of the generated token
* @since 1.8.0
*/
public String createToken(final Principal principal, final List<Permission> permissions, final IdentityProvider identityProvider) {
final Date today = new Date();
final JwtBuilder jwtBuilder = Jwts.builder();
jwtBuilder.setSubject(principal.getName());
jwtBuilder.setIssuer(ISSUER);
jwtBuilder.setIssuedAt(today);
jwtBuilder.setExpiration(addDays(today, 7));
if (permissions != null) {
jwtBuilder.claim("permissions", permissions.stream()
.map(Permission::getName)
.collect(Collectors.joining(","))
);
}
if (identityProvider != null) {
jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, identityProvider.name());
} else {
if (principal instanceof LdapUser) {
jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.LDAP.name());
} else if (principal instanceof OidcUser) {
jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.OPENID_CONNECT.name());
} else {
jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.LOCAL.name());
}
}
return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
}
/**
* 从token中获取JWT中的负载
*/
private Claims getClaimsFromToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
LOGGER.info("JWT格式验证失败:{}", token);
}
return claims;
}
public Claims getClaimByToken(String token) {
try {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}catch (Exception e){
//logger.error("validate is token error", e.toString());
return null;
}
}
/**
* 创建jwt
*
* @param subject
* @param secret
* @param ttlMillis
* @return
*/
public static String createJWT(String subject, String secret, long ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey key = generalKey(secret);
JwtBuilder builder = Jwts.builder().setId("jwt").setIssuedAt(now).setSubject(subject)
.signWith(signatureAlgorithm, key);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
/**
* 生成jwt token
*
* @param username
* @return token
*/
public String generateToken(String username) {
Date nowDate = new Date();
return Jwts.builder()
.setHeaderParam("typ", "JWT")
// 后续获取 subject 是 username
.setSubject(username)
.setIssuedAt(nowDate)
.setExpiration(DateUtils.addDays(nowDate, expire))
// 这里我采用的是 HS512 算法
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
private String createTokenWithDifferentSignature() {
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
return Jwts.builder()
.setSubject("anonymous")
.signWith(otherKey, SignatureAlgorithm.HS512)
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
.compact();
}
/**
* 生成Token
*
* @param id 编号
* @param issuer 该JWT的签发者,是否使用是可选的
* @param subject 该JWT所面向的用户,是否使用是可选的;
* @param ttlMillis 签发时间 (有效时间,过期会报错)
* @return token String
*/
public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {
// 签名算法 ,将对token进行签名
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
// 生成签发时间
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
// 通过秘钥签名JWT
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
// Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(now)
.setSubject(subject)
.setIssuer(issuer)
.signWith(signatureAlgorithm, signingKey);
// if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
// Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}