public static String encode(String subject, ArrayList<String> roles) { // prepare expiration date according to application properties Date expDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(expDate); int unit; switch (applicationProperties.getTokenExpiration().getUnit()) { case "SECOND": unit = Calendar.SECOND; break; case "MINUTE": unit = Calendar.MINUTE; break; default: unit = Calendar.HOUR; } calendar.add(unit, applicationProperties.getTokenExpiration().getValue()); expDate = calendar.getTime(); return Jwts.builder().setSubject(subject).claim("roles", roles).setIssuedAt(new Date()).setExpiration(expDate) .signWith(SignatureAlgorithm.HS256, key).compact(); }
@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 ")) { ExceptionUtils.createUnauthorizedException("Missing or invalid Authorization header.", res); return; } try { final String token = authHeader.substring(7); // The part after "Bearer " final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); } catch (final Exception e) { ExceptionUtils.createUnauthorizedException("Invalid token", res); return; } chain.doFilter(req, res); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String authHeader = request.getHeader("authorization"); if (!"OPTIONS".equals(request.getMethod())) { if (authHeader == null || !authHeader.startsWith("Bearer ")) { throw new JwtAuthException(); } String token = authHeader.substring(7); try { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); AuthContext.addClaims(claims); } catch (Exception e) { LOG.error("JWT parse error.", e); throw new JwtAuthException(e); } } return true; }
public JwtToken createRefreshToken(UserContext userContext) { if (StringUtils.isBlank(userContext.getUsername())) { throw new IllegalArgumentException("Cannot create JWT Token without username"); } LocalDateTime currentTime = LocalDateTime.now(); Claims claims = Jwts.claims().setSubject(userContext.getUsername()); claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority())); String token = Jwts.builder() .setClaims(claims) .setIssuer(AppConfig.prop.getProperty("security.tokenIssuer")) .setId(UUID.randomUUID().toString()) .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant())) .setExpiration(Date.from(currentTime .plusMinutes(Long.parseLong(AppConfig.prop.getProperty("security.refreshTokenExpTime"))) .atZone(ZoneId.systemDefault()).toInstant())) .signWith(SignatureAlgorithm.HS512, AppConfig.prop.getProperty("security.tokenSigningKey")) .compact(); return new AccessJwtToken(token, claims); }
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); } }
public static boolean Verify(String jwt, String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
@SuppressWarnings("unchecked") private static void generateNewDeploymentToken(File tokenFile) throws IOException { deploymentHash = Util.computeSHA256(serverID); JSONObject root = new JSONObject(); root.put("timestamp", System.currentTimeMillis()); root.put("hash", deploymentHash); String jwt = Jwts.builder() .setPayload(root.toJSONString()) .signWith(SignatureAlgorithm.ES384, configuration.getServerPrivateKey()) .compact(); // Sign and build the JWT Util.putFileContents(jwt, tokenFile); logger.info("Generated new deployment token."); }
public static Authentication getAuthentication(HttpServletRequest request) { // 从Header中拿到token String token = request.getHeader(HEADER_STRING); if (token == null) { token = getTokenFromCookis(request); } if (token != null && !token.isEmpty()) { // 解析 Token Claims claims = Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody(); // 获取用户名 String user = claims.get("UserId").toString(); // 获取权限(角色) List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities")); // 返回验证令牌 return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null; } return null; }
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(); }
@Override public TokenDto generate(final String username, final String password) { if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { throw new BadCredentialsException("Input data can't be empty."); } final User user = userService.findByUsername(username); validateInputPassword(user.getPassword(), password); final Map<String, Object> tokenData = new HashMap<>(); tokenData.put("username", user.getUsername()); tokenData.put("password", user.getPassword()); tokenData.put("create_date", LocalDateTime.now()); final JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setClaims(tokenData); final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, expirationTime); jwtBuilder.setExpiration(calendar.getTime()); final String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact(); return new TokenDto(token, mapper.map(user, UserDto.class)); }
/** * 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); }
/** * Get the user token witch can used to invoke personal api,such as get folder information * * @param userId The user you want to operate with * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60) * @return Detailed user access information * @throws YfyException */ public YfyAuthFinish getUserToken(long userId, int expirationTimeSeconds) throws YfyException { Claims claims = new DefaultClaims(); claims.put("yifangyun_sub_type", "user"); claims.setSubject(String.valueOf(userId)); 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); }
static void addAuthentication(HttpServletResponse response, String username) { // 生成JWT String JWT = Jwts.builder() // 保存权限(角色) .claim("authorities", "READ") // 用户名写入标题 .setSubject(username) // 有效期设置 .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // 签名设置 .signWith(SignatureAlgorithm.HS512, SECRET) .compact(); // 将 JWT 写入 body try { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().print("{\"token\":\"" + JWT + "\"}"); } catch (IOException e) { e.printStackTrace(); } }
@Override public JwtToken authenticate(Authentication authentication) throws AuthenticationException { JwtToken token = (JwtToken) authentication; if (token.getPrincipal() instanceof String) { try { Claims claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws((String) token.getPrincipal()) .getBody(); UserDetails user = handler.parseClaims(claims); return new JwtToken(user, claims, user.getAuthorities()); } catch (ClaimJwtException ex) { throw new BadCredentialsException("JWT error", ex); } } else { return null; } }
void addAuthentication(HttpServletResponse response, String username, Collection<? extends GrantedAuthority> authorities) throws IOException { List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); Claims claims = Jwts.claims() .setSubject(username) .setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000)); claims.put(ROLE_KEY, roles.stream().collect(Collectors.joining(ROLE_DELIMITER))); String JWT = Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret) .compact(); response.addHeader(headerString, headerStartWith + JWT); JwtAuthenticatedUser user = new JwtAuthenticatedUser(username, roles); PrintWriter printWriter = response.getWriter(); printWriter.print(mapper.writeValueAsString(user)); printWriter.flush(); }
@JsonView(Views.Public.class) @RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseEntity<?> login(@RequestBody LoginModel data) { User user = userService.getByUsername(data.getUsername()); if (user == null) { return new ResponseEntity(new LoginResponseBody(false, null, "User with that name isn't exist"), HttpStatus.OK); } if (!Objects.equals(user.getPassword(), MD5.getHash(data.getPassword()))) { return new ResponseEntity(new LoginResponseBody(false, null, "wrong_password"), HttpStatus.OK); } String token = Jwts.builder() .setSubject(data.getUsername()) .signWith(SignatureAlgorithm.HS512, key) .compact(); return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK); }
@JsonView(Views.Public.class) @RequestMapping(value = "/register", method = RequestMethod.POST) public ResponseEntity<?> register(@RequestBody LoginModel data) { User user = userService.getByUsername(data.getUsername()); if (user != null) { return new ResponseEntity(new LoginResponseBody(false, null, "User with that name has already existed"), HttpStatus.OK); } User newUser = new User(data.getUsername(), MD5.getHash(data.getPassword()), new Date(), "active", 0); userService.addUser(newUser); String token = Jwts.builder() .setSubject(newUser.getUsername()) .signWith(SignatureAlgorithm.HS512, key) .compact(); return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK); }
public boolean verifyToken(String token) { try { userName = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject(); isAuth = true; isAdmin = Objects.equals(userName, "admin"); message = "userName equals " + userName; return true; } catch (Exception e) { isAuth = false; isAdmin = false; message = e.getMessage(); return false; } }
@SuppressWarnings("Duplicates") @Override public Claims apply(String headerValue) { JwtParser parser = Jwts.parser(); if (signingKeyBytes != null) { parser.setSigningKey(signingKeyBytes); } else if (signingKey != null) { parser.setSigningKey(signingKey); } else if (signingKeyResolver != null) { parser.setSigningKeyResolver(signingKeyResolver); } if (this.allowedClockSkewSeconds != null) { parser.setAllowedClockSkewSeconds(this.allowedClockSkewSeconds); } return parser.parseClaimsJws(headerValue).getBody(); }
/** * Issue a JWT token * * @param authenticationTokenDetails * @return */ public String issueToken(AuthenticationTokenDetails authenticationTokenDetails) { return Jwts.builder() .setId(authenticationTokenDetails.getId()) .setIssuer(settings.getIssuer()) .setAudience(settings.getAudience()) .setSubject(authenticationTokenDetails.getUsername()) .setIssuedAt(Date.from(authenticationTokenDetails.getIssuedDate().toInstant())) .setExpiration(Date.from(authenticationTokenDetails.getExpirationDate().toInstant())) .claim(settings.getAuthoritiesClaimName(), authenticationTokenDetails.getAuthorities()) .claim(settings.getRefreshCountClaimName(), authenticationTokenDetails.getRefreshCount()) .claim(settings.getRefreshLimitClaimName(), authenticationTokenDetails.getRefreshLimit()) .signWith(SignatureAlgorithm.HS256, settings.getSecret()) .compact(); }
@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(); }
/** * 创建jwt * @param id * @param subject * @param ttlMillis * @return * @throws Exception */ public String createJWT(String id, String subject, long ttlMillis) throws Exception { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .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(); }
@Override public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(jwtProperties.getToken().getSecret()) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Try.of(() -> Arrays.stream(claims.get(jwtProperties.getToken().getPayload().getAuthoritiesKey()).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()) ).recover(ex -> Collections.emptyList() ).get(); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
private String createTokenWithDifferentSignature() { return Jwts.builder() .setSubject("anonymous") .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90") .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) .compact(); }
Optional<UserDetails> parseUserFromToken(String token) { String username = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody() .getSubject(); return Optional.ofNullable(userService.loadUserByUsername(username)); }
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(); }
public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature: " + e.getMessage()); return false; } }
private static JwtBuilder createJwtBuilderWithClaimMap(Map<String, Object> claimMap) { byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("testKey"); Key signingKey = new SecretKeySpec(apiKeySecretBytes, SIGNATURE_ALGORITHM.getJcaName()); LocalDate now = LocalDate.now(); LocalDate expirationDate = LocalDate.of(2020, 12, 31); return Jwts.builder() .setIssuedAt(valueOf(now)) .setClaims(claimMap) .setIssuer("testing-org") .setExpiration(valueOf(expirationDate)) .signWith(SIGNATURE_ALGORITHM, signingKey); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { try { String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); String token = authorizationHeader.substring("Bearer".length()).trim(); Jwts.parser().setSigningKey(keyGenerator.getKey()).parseClaimsJws(token); } catch (Exception e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } }
private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; } return claims; }
private void validateTokenData(final String token, final User user) { final Jws<Claims> tokenData = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); final String username = tokenData.getBody().get("username").toString(); final String password = tokenData.getBody().get("password").toString(); final User userFromToken = userService.findByUsername(username); assertEquals(user.getUsername(), userFromToken.getUsername()); assertEquals(user.getPassword(), password); }
String[] getPrincipalsAndCredentials(String authorizeParam) { Jws<Claims> claims = Jwts.parser() .setSigningKey(TokenRepository.SECURET.getBytes()) .parseClaimsJws(authorizeParam); String email = claims.getBody().getSubject(); return new String[]{email, authorizeParam}; }
public static void addAuthentication(HttpServletResponse response, String username) throws IOException { UserDetailsEntity userDetailsEntity = jwtService.userDetailsService.findById(username); if (userDetailsEntity == null) { logger.info("用户{}不存在:", username); response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } // 生成JWT String JWT = Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET) .setHeaderParam("alg", "HS256") .setHeaderParam("typ", "JWT") // 有效期设置 .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) // 用户名写入标题 .setIssuer("hzwy23") .claim("UserId", userDetailsEntity.getUser_id()) .claim("DomainId", userDetailsEntity.getDomain_id()) .claim("OrgUnitId", userDetailsEntity.getOrg_unit_id()) // 保存权限(角色) .claim("authorities", JWT_ROLES) // 签名设置 .compact(); responseJWT(response, JWT); }
/** * 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 * @return a String representation of the generated token * @since 1.0.0 */ public String createToken(Principal principal) { final Date today = new Date(); final JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setSubject(principal.getName()); jwtBuilder.setIssuer("Alpine"); jwtBuilder.setIssuedAt(today); jwtBuilder.setExpiration(addDays(today, 7)); return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact(); }
private Claims getBody(String token) { if (token != null) { try { return Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) .getBody(); } catch (Exception exception) { return null; } } return null; }
String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
public static String parseToken(HttpServletRequest httpServletRequest, String jwtTokenCookieName, String signingKey){ String token = CookieUtil.getValue(httpServletRequest, jwtTokenCookieName); if(token == null) { return null; } String subject = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody().getSubject(); if (!RedisUtil.INSTANCE.sismember(REDIS_SET_ACTIVE_SUBJECTS, subject)) { return null; } return subject; }
private String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }