public JwtToken createRefreshToken(UserContext userContext) { if (StringUtils.isBlank(userContext.getTenantId())) throw new IllegalArgumentException("Cannot create JWT Token without tenantId"); if (StringUtils.isBlank(userContext.getOrgId())) throw new IllegalArgumentException("Cannot create JWT Token without orgId"); DateTime currentTime = new DateTime(); Claims claims = Jwts.claims().setSubject(userContext.getOrgId()); claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList())); claims.put("tenant", userContext.getTenantId()); String token = Jwts.builder() .setClaims(claims) .setIssuer(settings.getTokenIssuer()) .setId(UUID.randomUUID().toString()) .setIssuedAt(currentTime.toDate()) .setExpiration(currentTime.plusMinutes(settings.getRefreshTokenExpTime()).toDate()) .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()) .compact(); return new AccessJwtToken(token, claims); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final JwtToken token = (JwtToken) authentication.getCredentials(); final Claims claims = jwt.validate(token); final String userId = claims.getSubject(); final String email = claims.get("mail", String.class); @SuppressWarnings("unchecked") final List<String> scopes = (List<String>) claims.get("scopes", List.class); final List<GrantedAuthority> auths = scopes.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); final JwtUserDetails user = new JwtUserDetails(userId, email, auths); return new JwtAuthentication(token, user); }
@Test public void sign_token_with_KMS_and_verify() throws Exception { String[] params = { "--region", TEST_AWS_REGION, "--key", TEST_AWS_KEY_ARN, "--username", "userXYZ", "--journey", "SUM,UPR", }; GenerateTokenApp.main(params); String jwtToken = getTokenFromStdout(); System.out.println("jwt: "+jwtToken); KMSDecrypt kmsDecrypt = new KMSDecrypt(KMS_CLIENT, Collections.singleton(TEST_AWS_KEY_ARN)); Claims claims = new JWTDecoder(kmsDecrypt).decodeAndVerify(jwtToken); assertThat(claims.get("usr"), is("userXYZ")); }
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(); }
/** * Get the enterprise token witch can used to invoke admin api,such as managing departments and groups * * @param enterpriseId Your enterprise id * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60) * @return Detailed user access information * @throws YfyException */ public YfyAuthFinish getEnterpriseToken(long enterpriseId, int expirationTimeSeconds) throws YfyException { Claims claims = new DefaultClaims(); claims.put("yifangyun_sub_type", "enterprise"); claims.setSubject(String.valueOf(enterpriseId)); claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds)); claims.setIssuedAt(new Date()); claims.setId(getGeneratedJwtId(16)); final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact(); return YfyRequestUtil.doPostInAuth( requestConfig, YfyAppInfo.getHost().getAuth(), "oauth/token", new HashMap<String, String>() {{ put("grant_type", "jwt"); put("assertion", compactJws); }}, YfyAuthFinish.class); }
/** * Clients should call this in order to refresh a JWT. * * @param request the request from the client. * @return the JWT with an extended expiry time if the client was authenticated, a 400 Bad Request otherwise. */ @RequestMapping(value = "/refresh", method = RequestMethod.GET) public ResponseEntity<?> refreshAuthenticationToken(HttpServletRequest request) { final String authorizationHeader = request.getHeader("Authorization"); final Claims claims = jwtUtils.validateTokenAndGetClaims(authorizationHeader); final String username = jwtUtils.getUsernameFromTokenClaims(claims); final JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username); if (jwtUtils.canTokenBeRefreshed(claims, new Date(user.getLastPasswordResetDate()))) { final String refreshedToken = jwtUtils.refreshToken(authorizationHeader); return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken)); } else { return ResponseEntity.badRequest().body(null); } }
@GetMapping("/specials/captcha") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception { Claims claims = (Claims) request.getAttribute(AppConstants.CLAIMS); // 缓存验证码数值 CaptchaGenerator instance = CaptchaGenerator.INSTANCE; BufferedImage bi = instance.genImage(); specialService.saveCaptcha(claims, instance.getCaptcha()); // 输出验证码图片 response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/JPEG"); ImageIO.write(bi, "JPEG", response.getOutputStream()); response.getOutputStream().flush(); }
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 String keyId = claims.get(KEY_ID_CLAIM, String.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 MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) { // TODO: Exercise all exceptions to ensure none leak key material to logs final String errorMessage = "Unable to validate the access token."; throw new JwtException(errorMessage, e); } }
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final String authHeader = request.getHeader("Authorization"); if (authHeader == null || !authHeader.startsWith("Bearer ")) { throw new ServletException("Missing or invalid Authorization header."); } final String token = authHeader.substring(7); // The part after "Bearer " try { final Claims claims = Jwts.parser().setSigningKey("secretkey") .parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); } catch (final SignatureException e) { throw new ServletException("Invalid token."); } chain.doFilter(req, res); }
@Override public String createJwtToken(Authentication authentication, int minutes) { Claims claims = Jwts.claims() .setId(String.valueOf(IdentityGenerator.generate())) .setSubject(authentication.getName()) .setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000)) .setIssuedAt(new Date()); String authorities = authentication.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .map(String::toUpperCase) .collect(Collectors.joining(",")); claims.put(AUTHORITIES, authorities); return Jwts.builder() .setClaims(claims) .signWith(HS512, secretkey) .compact(); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials(); Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey()); String orgId = jwsClaims.getBody().getSubject(); String tenantId = jwsClaims.getBody().get("tenant", String.class); List<String> scopes = jwsClaims.getBody().get("scopes", List.class); List<GrantedAuthority> authorities = scopes.stream() .map(authority -> new SimpleGrantedAuthority(authority)) .collect(Collectors.toList()); UserContext context = UserContext.create(tenantId, orgId, authorities); return new JwtAuthenticationToken(context, context.getAuthorities()); }
@Override public JsonResult executeSignOut(HttpServletRequest request, HttpServletResponse response) { JsonResult result = new JsonResult(); Cookie tokenCookie = CookieUtil.getCookieByName(request, AppConstants.ACCESS_TOKEN); if (tokenCookie != null) { Claims requestClaims = JwtTokenUtil.getClaims(tokenCookie.getValue(), appProperties.getJwtSecretKey()); // 清除缓存 String cacheKey = AppConstants.CACHE_ACCESS_TOKEN + requestClaims.getAudience(); byteRedisClient.del(cacheKey); } // 清除Cookie CookieUtil.removeCookie(AppConstants.ACCESS_TOKEN, "lovexq.net", response); CookieUtil.removeCookie(AppConstants.USER_NAME, "lovexq.net", response); return result; }
public String getAudienceFromToken(String token) { String audience; try { final Claims claims = getClaimsFromToken(token); audience = (String) claims.get(CLAIM_KEY_AUDIENCE); } catch (Exception e) { audience = null; } return audience; }
/** * @param token * @return */ public String getAudienceFromToken ( String token ) { String audience; try { final Claims claims = getClaimsFromToken( token ); audience = ( String ) claims.get( CLAIM_KEY_AUDIENCE ); } catch ( Exception e ) { audience = null; } return audience; }
private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; } return claims; }
private Claims getClaimsFromToken(String token) { return Jwts.parser() .requireIssuer(ISSUER) .requireAudience(AUDIENCE) .setSigningKey(secret) .parseClaimsJws(token) .getBody(); }
public String refreshToken(String token) { final Date createdDate = timeProvider.now(); final Date expirationDate = calculateExpirationDate(createdDate); final Claims claims = getAllClaimsFromToken(token); claims.setIssuedAt(createdDate); claims.setExpiration(expirationDate); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
/** * Retorna a data de expiração de um token JWT. * * @param token * @return Date */ public Date getExpirationDateFromToken(String token) { Date expiration; try { Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; }
public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
public Date getExpirationDateFromToken(String token) { Date expiration; try { final Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; }
/** * Realiza o parse do token JWT para extrair as informações contidas no * corpo dele. * * @param token * @return Claims */ private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } catch (Exception e) { claims = null; } return claims; }
@Test public void testJWTAuthentication_signed_asymmetric() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(512); KeyPair keyPair = keyGen.genKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); final JwtConfiguration cfg = JwtConfiguration.builder().signatureAlgorithm(SignatureAlgorithm.RS256.getValue()) .privateKey(privateKey).publicKey(publicKey).build(); final Realm realm = Realm.builder().authenticator(JwtAuthenticator.builder().configuration(cfg).build()) .build(); Authentication authc = Authentication.builder("testuser").root(true).build(); String jwt = JwtTokenBuilder.buildJWT(authc, "TestId", "TestUnit", 20000L, SignatureAlgorithm.RS256, privateKey); assertNotNull(jwt); Authentication authenticated = realm.authenticate(AuthenticationToken.bearer(jwt)); assertNotNull(authenticated); assertEquals(authc, authenticated); assertEquals("TestUnit", authenticated.getParameter(Claims.ISSUER, String.class).get()); assertEquals("TestId", authenticated.getParameter(Claims.ID, String.class).get()); }
public String getUsernameFromToken(String token) { String username; try { final Claims claims = this.getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
public String getYbaccessToken(String token) { String ybtoken; try { final Claims claims = getClaimsFromToken(token); ybtoken = claims.get(YBACCESS_TOKEN).toString(); } catch (Exception e) { ybtoken = null; } return ybtoken; }
@Override @Transactional(readOnly = true) public JsonResult exposureSecKillUrl(Long id, Claims claims) throws Exception { String account = claims.getAudience(); SpecialStockDTO specialStock = getOne(id); LocalDateTime startTime = specialStock.getStartTime(); // 秒杀开始时间 LocalDateTime endTime = specialStock.getEndTime(); // 秒杀结束时间 LocalDateTime nowTime = TimeUtil.nowDateTime(); //系统当前时间 //若是秒杀未开始 if (startTime.isAfter(nowTime)) { return new JsonResult(406, "秒杀活动未开始!"); //秒杀已经结束 } else if (endTime.isBefore(nowTime) || specialStock.getNumber() < 1) { return new JsonResult(406, "秒杀活动已经结束!"); //秒杀处于开启窗口 } else { // 检查是否秒杀过 SpecialOrderModel order = specialOrderRepository.findByStockIdAndAccount(id, account); if (order != null) { return new JsonResult(403, "已秒杀成功,请勿重复秒杀!"); } return new JsonResult(getMd5Url(id)); } }
public String refreshToken(String token) { String refreshedToken; try { final Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; }
/** * Cria um novo token (refresh). * * @param token * @return String */ public String refreshToken(String token) { String refreshedToken; try { Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = gerarToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; }
@Override public Key resolveSigningKey(JwsHeader header, Claims claims) { Key result = delegate.resolveSigningKey(header, claims); if (result == null) { result = this.fallbackKey; } return result; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials(); Jws<Claims> jwsClaims = rawAccessToken.parseClaims(AppConfig.prop.getProperty("security.tokenSigningKey")); String subject = jwsClaims.getBody().getSubject(); List<String> scopes = jwsClaims.getBody().get("scopes", List.class); List<GrantedAuthority> authorities = scopes.stream() .map(authority -> new SimpleGrantedAuthority(authority)) .collect(Collectors.toList()); UserContext context = UserContext.create(subject, authorities); return new JwtAuthenticationToken(context, context.getAuthorities()); }
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) { Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey()); Claims claims = jwsClaims.getBody(); String subject = claims.getSubject(); List<String> scopes = claims.get(SCOPES, List.class); if (scopes == null || scopes.isEmpty()) { throw new IllegalArgumentException("JWT Token doesn't have any scopes"); } SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class)))); securityUser.setEmail(subject); securityUser.setAuthority(Authority.parse(scopes.get(0))); securityUser.setFirstName(claims.get(FIRST_NAME, String.class)); securityUser.setLastName(claims.get(LAST_NAME, String.class)); securityUser.setEnabled(claims.get(ENABLED, Boolean.class)); boolean isPublic = claims.get(IS_PUBLIC, Boolean.class); UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject); securityUser.setUserPrincipal(principal); String tenantId = claims.get(TENANT_ID, String.class); if (tenantId != null) { securityUser.setTenantId(new TenantId(UUID.fromString(tenantId))); } String customerId = claims.get(CUSTOMER_ID, String.class); if (customerId != null) { securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId))); } return securityUser; }
public String createToken(String username, List<Role> roles) { Claims claims = Jwts.claims().setSubject(username); claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList())); Date now = new Date(); Date validity = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder()// .setClaims(claims)// .setIssuedAt(now)// .setExpiration(validity)// .signWith(SignatureAlgorithm.HS256, secretKey)// .compact(); }
/** * Verifies a web token given a username and token * Checks the given username with the token username to verify usage * * @param token JavaScript Web Token * @param username the given username * @return true if token is fine, otherwise false */ public static boolean verify(String token, String username) { Claims claims = null; UserDaoImpl ud = new UserDaoImpl(); User user = null; String cUsername = null; boolean verified = false; if(token == null) { return false; } try { claims = Jwts.parser() .setSigningKey(getSecret()) .parseClaimsJws(token).getBody(); cUsername = claims.getSubject(); user = ud.getUserByUsername(cUsername); if(cUsername == null || user == null || !cUsername.equals(username)) { return false; } verified = true; }catch(SignatureException se) { } return verified; }
/** * Checks if use is an admin * * @param token the JWT given * @return true if admin exists, false otherwise */ public static boolean isAdmin(String token) { Claims claims = null; UserDaoImpl ud = new UserDaoImpl(); User user = null; String cUsername = null; boolean verified = false; if(token == null) { return false; } try { claims = Jwts.parser() .setSigningKey(getSecret()) .parseClaimsJws(token).getBody(); cUsername = claims.getSubject(); user = ud.getUserByUsername(cUsername); if(cUsername == null || user == null || user.getRoleFlag() != 2) { return false; } verified = true; }catch(SignatureException se) { se.printStackTrace(); } return verified; }
public JwtToken(UserDetails principal, Claims claims, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; this.claims = claims; setAuthenticated(true); setDetails(principal); }