Java Examples for io.jsonwebtoken.Jwts
The following java examples will help you to understand the usage of io.jsonwebtoken.Jwts. These source code samples are taken from different open source projects.
Example 1
Project: spark-jwt-auth-master File: TokenValidator.java View source code |
public boolean validate(String token) { boolean valid = false; Object username = Jwts.parser().setSigningKey(Constant.JWT_SECRET).parseClaimsJws(token).getBody().get("username"); Object password = Jwts.parser().setSigningKey(Constant.JWT_SECRET).parseClaimsJws(token).getBody().get("password"); Object expireTime = Jwts.parser().setSigningKey(Constant.JWT_SECRET).parseClaimsJws(token).getBody().get("expireTime"); Long currentTimeInMilisecond = timeProvider.getCurrentTime(); if (IUserRepository.getUser().getUsername().equals(username) && IUserRepository.getUser().getPassword().equals(password) && (Long) expireTime > currentTimeInMilisecond) { valid = true; } return valid; }
Example 2
Project: jwt-angular-spring-master File: UserController.java View source code |
@RequestMapping(value = "login", method = RequestMethod.POST)
public LoginResponse login(@RequestBody final UserLogin login) throws ServletException {
if (login.name == null || !userDb.containsKey(login.name)) {
throw new ServletException("Invalid login");
}
return new LoginResponse(Jwts.builder().setSubject(login.name).claim("roles", userDb.get(login.name)).setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256, "secretkey").compact());
}
Example 3
Project: mangooio-master File: OutboundCookiesHandler.java View source code |
/**
* Sets the session cookie to the current HttpServerExchange
*
* @param exchange The Undertow HttpServerExchange
*/
protected void setSessionCookie(HttpServerExchange exchange) {
Session session = this.attachment.getSession();
if (session != null && session.hasChanges()) {
Map<String, Object> claims = new HashMap<>();
claims.put(ClaimKey.AUTHENTICITY.toString(), session.getAuthenticity());
claims.put(ClaimKey.VERSION.toString(), this.config.getCookieVersion());
claims.put(ClaimKey.DATA.toString(), session.getValues());
final LocalDateTime expires = session.getExpires();
String jwt = Jwts.builder().setClaims(claims).setExpiration(DateUtils.localDateTimeToDate(expires)).signWith(SignatureAlgorithm.HS512, this.config.getApplicationSecret()).compact();
if (this.config.isSessionCookieEncrypt()) {
jwt = this.attachment.getCrypto().encrypt(jwt);
}
final Cookie cookie = CookieBuilder.create().name(this.config.getSessionCookieName()).value(jwt).secure(this.config.isSessionCookieSecure()).httpOnly(true).expires(expires).build();
exchange.setResponseCookie(cookie);
}
}
Example 4
Project: MMS-master File: AccessTokenTest.java View source code |
@Test
public void testOptionalValues() {
Jwt token = new AccessToken.Builder(ACCOUNT_SID, SIGNING_KEY_SID, SECRET).identity(ACCOUNT_SID).nbf(new Date()).build();
Claims claims = Jwts.parser().setSigningKey(SECRET.getBytes()).parseClaimsJws(token.toJwt()).getBody();
validateToken(claims);
Assert.assertTrue(claims.getNotBefore().getTime() <= new Date().getTime());
}
Example 5
Project: WebAPI-master File: TokenManager.java View source code |
public static String createJsonWebToken(String subject, Date expiration, Collection<String> permissions) {
Key key = MacProvider.generateKey();
userToKeyMap.put(subject, key);
String permissionsString = StringUtils.join(permissions, "|");
Map<String, Object> claims = new HashMap<>();
claims.put("permissions", permissionsString);
return Jwts.builder().setClaims(claims).setSubject(subject).setExpiration(expiration).signWith(SignatureAlgorithm.HS512, key).compact();
}
Example 6
Project: stormpath-sdk-java-master File: WriteCacheFilter.java View source code |
private void uncacheRevokedToken(Map<String, Object> data) {
String token = data.get(OAuthTokenRevocationAttempt.TOKEN.getName()).toString();
int signatureIndex = token.lastIndexOf('.');
if (signatureIndex <= 0) {
return;
}
Object typeObject = data.get(OAuthTokenRevocationAttempt.TOKEN_TYPE_HINT.getName());
String tokenTypeHint = null;
if (typeObject instanceof String) {
tokenTypeHint = typeObject.toString();
}
try {
String nonSignedToken = token.substring(0, signatureIndex + 1);
Jwt<Header, Claims> jwt = Jwts.parser().parseClaimsJwt(nonSignedToken);
Object stt = jwt.getHeader().get("stt");
String rti = null;
Claims body = jwt.getBody();
if ("refresh".equals(stt) || "refresh_token".equals(tokenTypeHint)) {
rti = body.getId();
} else if ("access".equals(stt) || "access_token".equals(tokenTypeHint)) {
rti = body.get("rti", String.class);
}
if (rti != null) {
String href = baseUrlResolver.getBaseUrl() + "/refreshTokens/" + rti;
uncache(href, RefreshToken.class);
}
} catch (//ignored
Exception //ignored
e) {
}
}
Example 7
Project: devicehive-java-server-master File: JwtTokenResourceTest.java View source code |
@Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void should_return_401_after_providing_expired_refresh_token() throws Exception { // Create test user UserVO testUser = new UserVO(); testUser.setLogin("string_3"); testUser.setRole(UserRole.CLIENT); testUser.setPasswordHash("string_3"); testUser.setStatus(UserStatus.ACTIVE); UserVO user = performRequest("/user", "POST", emptyMap(), singletonMap(HttpHeaders.AUTHORIZATION, basicAuthHeader(ADMIN_LOGIN, ADMIN_PASS)), testUser, CREATED, UserVO.class); final long userid = user.getId(); // Create payload Long userId = userid; Set<String> actions = new HashSet<>(); actions.add("string"); Set<String> networkIds = new HashSet<>(); networkIds.add("string"); Set<String> deviceGuids = new HashSet<>(); deviceGuids.add("string"); JwtPayload.Builder builder = new JwtPayload.Builder(); JwtPayload payload = builder.withPublicClaims(userId, actions, networkIds, deviceGuids).buildPayload(); // Generate expired refresh token payload.setExpiration(new Date(System.currentTimeMillis() - 100)); payload.setTokenType(TokenType.REFRESH); Map<String, Object> jwtMap = new HashMap<>(); jwtMap.put(JwtPayload.JWT_CLAIM_KEY, payload); Claims claims = Jwts.claims(jwtMap); String refreshToken = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, secret).compact(); JwtTokenVO tokenVO = new JwtTokenVO(); tokenVO.setRefreshToken(refreshToken); JwtTokenVO jwtToken = performRequest("/token/refresh", "POST", emptyMap(), emptyMap(), tokenVO, UNAUTHORIZED, JwtTokenVO.class); assertNull(jwtToken.getAccessToken()); }
Example 8
Project: webengineering-2017-master File: AuthenticationService.java View source code |
/**
* Create a JWT token and additional user information if the user's credentails are valid.
*
* @param email email
* @param password password
* @return a UserToken or null if the credentials are not valid
*/
public UserToken login(String email, String password) {
String hashedPassword = hashPassword(password);
User user = userService.getUser(email, hashedPassword);
if (user == null) {
LOG.info("User unable to login. user={}", email);
return null;
}
LOG.info("User successfully logged in. user={}", email);
String token = Jwts.builder().setSubject(email).setId(user.getId().toString()).signWith(SignatureAlgorithm.HS512, JWTSecret).compact();
UserToken userToken = new UserToken();
userToken.user = user;
userToken.token = token;
return userToken;
}
Example 9
Project: springboot-dubbox-master File: AbstractTokenUtil.java View source code |
/**
* 生成 Token
*
* @param userDetails 用户信息
* @return String
*/
public String generateToken(UserDetails userDetails) {
String token = Jwts.builder().setSubject(userDetails.getUsername()).setExpiration(generateExpired()).signWith(SignatureAlgorithm.HS512, secret).compact();
String key = REDIS_PREFIX_AUTH + userDetails.getUsername();
redisRepository.setExpire(key, token, expiration);
putUserDetails(userDetails);
return token;
}
Example 10
Project: uPortal-master File: AbstractJwtService.java View source code |
protected Jws<Claims> parseEncrypteToken(String encryptedToken, Class<? extends ITokenizable> clazz) {
// Decryption
final String jwt = textEncryptor.decrypt(encryptedToken);
final Jws<Claims> rslt = Jwts.parser().setSigningKey(signatureKey).parseClaimsJws(jwt);
// Token expired?
final Date expires = rslt.getBody().getExpiration();
if (expires.before(new Date())) {
final String msg = "The specified token is expired: " + rslt;
throw new SecurityException(msg);
}
// Sanity check
final String s = (String) rslt.getBody().get(JwtClaims.CLASS.getName());
if (!clazz.getName().equals(s)) {
// Opportunity for future versioning of the data model... needs work
String msg = "Token class mismatch; expected '" + clazz.getName() + "' but was '" + s + "'";
throw new RuntimeException(msg);
}
return rslt;
}
Example 11
Project: MaritimeCloud-master File: JwtAuthenticationTokenHandler.java View source code |
/**
* Resolves an {@code AuthenticationToken} from the websocket upgrade request bearer authorization header.
* If none can be resolved, null is returned.
* If the JWT token is present but invalid, an AuthenticationException is thrown
*
* @param jwtSecret the shared JWT secret
* @param authHeader the authorization header
* @return the authentication token, or null if none is resolved
*/
public static AuthenticationToken resolveAuthenticationToken(String jwtSecret, String authHeader) throws AuthenticationException {
if (authHeader != null && authHeader.startsWith("Bearer ")) {
// Extract the user part from the header
String jwt = authHeader.substring("Bearer ".length());
try {
// Throws an JwtException in case of error (e.g. expired)
Claims claims = Jwts.parser().setSigningKey(jwtSecret.getBytes("UTF-8")).parseClaimsJws(jwt).getBody();
return new JwtAuthenticationToken(claims.getSubject());
} catch (Exception e) {
throw new AuthenticationException("Invalid JWT Token", e);
}
}
// No principal resolved
return null;
}
Example 12
Project: apiman-plugins-master File: JWTPolicyTest.java View source code |
@Test
@Configuration("{\n" + " \"requireJWT\": true,\n" + " \"requireSigned\": false,\n" + " \"requireTransportSecurity\": true,\n" + " \"stripTokens\": true,\n" + " \"signingKeyString\": \"" + PUBLIC_KEY_PEM + "\",\n" + " \"allowedClockSkew\": 0,\n" + " \"requiredClaims\": [{ \"claimName\": \"sub\", \"claimValue\": \"aride\" }],\n" + " \"forwardAuthInfo\": [{ \"header\": \"X-Foo\", \"field\": \"sub\" }]\n" + "}")
public void shouldForwardClaimsAsHeaders() throws Throwable {
PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/amirante").header(AUTHORIZATION, "Bearer " + Jwts.builder().setSubject("aride").compact());
PolicyTestResponse response = send(request);
EchoResponse echo = response.entity(EchoResponse.class);
Assert.assertNotNull(echo);
Assert.assertEquals("aride", echo.getHeaders().get("X-Foo"));
}
Example 13
Project: sonarqube-master File: JwtSerializerTest.java View source code |
@Test
public void return_no_token_when_expiration_date_is_reached() throws Exception {
setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder().setId("123").setIssuedAt(new Date(system2.now())).setExpiration(new Date(system2.now())).signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)).compact();
assertThat(underTest.decode(token)).isEmpty();
}
Example 14
Project: user-master File: ExternalSSOEnabledIT.java View source code |
private String genrateToken() {
Map<String, Object> claims = new HashedMap<String, Object>();
claims.put("jti", "c7df0339-3847-450b-a925-628ef237953a");
claims.put("sub", "b6d62259-217b-4e96-8f49-e00c366e4fed");
claims.put("scope", "size = 5");
claims.put("client_id", "edgecli");
claims.put("azp", "edgecli");
claims.put("grant_type", "password");
claims.put("user_id", "b6d62259-217b-4e96-8f49-e00c366e4fed");
claims.put("origin", "usergrid");
claims.put("user_name", "AyeshaSSOUser");
claims.put("email", "adastagiri+ssotesting@apigee.com");
claims.put("rev_sig", "dfe5d0d3");
claims.put("iat", "1466550862");
claims.put("exp", System.currentTimeMillis() + 1000);
claims.put("iss", "https://login.apigee.com/oauth/token");
claims.put("zid", "uaa");
claims.put("aud", " size = 6");
claims.put("grant_type", "password");
String jwt = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKey).compact();
return jwt;
}
Example 15
Project: nifi-master File: JwtService.java View source code |
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtExceptionUnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException | e) {
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
Example 16
Project: thingsboard-master File: AbstractControllerTest.java View source code |
protected void validateJwtToken(String token, String username) {
Assert.assertNotNull(token);
Assert.assertFalse(token.isEmpty());
int i = token.lastIndexOf('.');
Assert.assertTrue(i > 0);
String withoutSignature = token.substring(0, i + 1);
Jwt<Header, Claims> jwsClaims = Jwts.parser().parseClaimsJwt(withoutSignature);
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
Assert.assertEquals(username, subject);
}
Example 17
Project: ambari-master File: LogsearchJWTFilter.java View source code |
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (StringUtils.isEmpty(authPropsConfig.getProvidedUrl())) {
throw new BadCredentialsException("Authentication provider URL must not be null or empty.");
}
if (StringUtils.isEmpty(authPropsConfig.getPublicKey())) {
throw new BadCredentialsException("Public key for signature validation must be provisioned.");
}
try {
Claims claims = Jwts.parser().setSigningKey(parseRSAPublicKey(authPropsConfig.getPublicKey())).parseClaimsJws(getJWTFromCookie(request)).getBody();
String userName = claims.getSubject();
LOG.info("USERNAME: " + userName);
LOG.info("URL = " + request.getRequestURL());
if (StringUtils.isNotEmpty(claims.getAudience()) && !authPropsConfig.getAudiences().contains(claims.getAudience())) {
throw new IllegalArgumentException(String.format("Audience validation failed. (Not found: %s)", claims.getAudience()));
}
Authentication authentication = new JWTAuthenticationToken(userName, authPropsConfig.getPublicKey());
authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication;
} catch (ExpiredJwtExceptionMalformedJwtException | SignatureException | IllegalArgumentException | e) {
LOG.info("URL = " + request.getRequestURL());
LOG.warn("Error during JWT authentication: ", e.getMessage());
throw new BadCredentialsException(e.getMessage(), e);
}
}
Example 18
Project: acme-client-master File: Acme.java View source code |
@SuppressWarnings("serial")
protected String getAuthorizationRequest(final KeyPair userKey, final String nextNonce, final String domain) {
return Jwts.builder().setHeaderParam(NONCE_KEY, nextNonce).setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic())).setClaims(new TreeMap<String, Object>() {
{
put(RESOURCE_KEY, RESOURCE_NEW_AUTHZ);
put(IDENTIFIER_KEY, new TreeMap<String, Object>() {
{
put(IDENTIFIER_TYPE_KEY, IDENTIFIER_TYPE_DNS);
put(IDENTIFIER_VALUE_KEY, domain);
}
});
}
}).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact();
}
Example 19
Project: datacollector-master File: OAuth2ConfigBean.java View source code |
@SuppressWarnings("unchecked")
private void insertJWTFields(MultivaluedMap<String, String> requestValues) throws IOException {
String parsedJwt;
try {
parsedJwt = timeEvaluator.eval(elVars, jwtClaims, String.class);
} catch (// NOSONAR
Exception // NOSONAR
ex) {
throw new RuntimeException(ex);
}
Map<String, Object> claims = (Map<String, Object>) OBJECT_MAPPER.readValue(parsedJwt, Map.class);
JwtBuilder builder = Jwts.builder().setClaims(claims);
try {
if (isRSA()) {
builder.signWith(JWTUtils.getSignatureAlgorithm(algorithm), privateKey);
} else if (isHMAC()) {
builder.signWith(JWTUtils.getSignatureAlgorithm(algorithm), key);
}
Map<String, Object> header = new HashMap<>(1);
header.put(Header.TYPE, Header.JWT_TYPE);
builder.setHeader(header);
String base64EncodedJWT = builder.compact();
requestValues.put(GRANT_TYPE_KEY, Collections.singletonList(JWT_GRANT_TYPE));
requestValues.put(ASSERTION_KEY, Collections.singletonList(base64EncodedJWT));
} catch (Exception ex) {
throw new IOException(ex);
}
}
Example 20
Project: obiba-commons-master File: ObibaRealm.java View source code |
private Jwt<Header, Claims> getWebTokenFromPrincipals(Collection<?> principals) {
for (Object principal : principals) {
try {
String[] webTokenParts = ((String) principal).split("\\.");
if (webTokenParts.length > 1) {
//do not validate signature
String webToken = String.format("%s.%s.", webTokenParts[0], webTokenParts[1]);
return Jwts.parser().parse(webToken);
}
} catch (MalformedJwtException e) {
}
}
return null;
}
Example 21
Project: spring-security-jwt-master File: TokenHandler.java View source code |
public User parseUserFromToken(String token) {
String username = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
return userService.loadUserByUsername(username);
}
Example 22
Project: reactor-master File: UsernameProvider.java View source code |
private String getUsername(String token) {
Jws<Claims> jws = Jwts.parser().setSigningKeyResolver(this.signingKeyResolver).parseClaimsJws(token);
return Optional.ofNullable(jws.getBody().get("user_name", String.class)).orElseThrow(() -> new IllegalStateException("Unable to retrieve username from token"));
}
Example 23
Project: jhipster4-demo-master File: TokenProviderTest.java View source code |
private String createUnsupportedToken() {
return Jwts.builder().setPayload("payload").signWith(SignatureAlgorithm.HS512, secretKey).compact();
}
Example 24
Project: spring-boot-tut-master File: JwtTokenUtil.java View source code |
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}