Java 类io.jsonwebtoken.Jwts 实例源码

项目:yum    文件:JwtCodec.java   
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();

}
项目:IPPR2016    文件:JwtFilter.java   
@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);
}
项目:uroborosql-springboot-demo    文件:AuthInterceptor.java   
@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;
}
项目:infotaf    文件:JwtTokenFactory.java   
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);
}
项目:nifi-registry    文件:JwtService.java   
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);
    }
}
项目:SistemaAlmoxarifado    文件:Token.java   
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;
    }
}
项目:nectar-server    文件:NectarServerApplication.java   
@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.");
}
项目:hauth-java    文件:JwtService.java   
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;
    }
项目:hauth-java    文件:JwtService.java   
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();
}
项目:product-management-system    文件:JwtService.java   
@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));
}
项目:fangcloud-java-sdk    文件:YfyEnterpriseAuth.java   
/**
 * 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);
}
项目:fangcloud-java-sdk    文件:YfyEnterpriseAuth.java   
/**
 * 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);
}
项目:fish-admin    文件:TokenAuthenticationService.java   
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();
        }
    }
项目:ARCLib    文件:JwtTokenProvider.java   
@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;
    }
}
项目:PepSIIrup-2017    文件:TokenAuthenticationService.java   
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();
}
项目:spring-mvc-react    文件:AuthorizationController.java   
@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);
}
项目:spring-mvc-react    文件:AuthorizationController.java   
@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);
}
项目:spring-mvc-react    文件:AuthService.java   
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;
        }
    }
项目:juiser    文件:JwsClaimsExtractor.java   
@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();
}
项目:jersey-jwt    文件:AuthenticationTokenIssuer.java   
/**
 * 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();
}
项目:springuni-particles    文件:JwtTokenServiceImpl.java   
@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();
}
项目:xmanager    文件:JwtUtil.java   
/**
 * 创建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();
}
项目:jwt-security-spring-boot-starter    文件:JJWTTokenProvider.java   
@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);
}
项目:jhipster-microservices-example    文件:TokenProviderTest.java   
private String createTokenWithDifferentSignature() {
    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90")
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
项目:SA-starter-kit    文件:TokenHandler.java   
Optional<UserDetails> parseUserFromToken(String token) {
    String username = Jwts.parser()
            .setSigningKey(secret)
            .parseClaimsJws(token)
            .getBody()
            .getSubject();
    return Optional.ofNullable(userService.loadUserByUsername(username));
}
项目:rest-api-jwt-spring-security    文件:JwtTokenUtil.java   
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();
}
项目:klask-io    文件:TokenProvider.java   
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;
    }
}
项目:qpp-conversion-tool    文件:JwtTestHelper.java   
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);
}
项目:Java-9-Programming-Blueprints    文件:SecureFilter.java   
@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());
    }
}
项目:springboot-rest-api-skeleton    文件:JwtTokenUtil.java   
private Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}
项目:product-management-system    文件:TokenServiceTest.java   
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);
}
项目:stateless-shiro    文件:BearerTokenAuthenticatingFilter.java   
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};
}
项目:hauth-java    文件:JwtService.java   
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);

}
项目:Alpine    文件:JsonWebToken.java   
/**
 * 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();
}
项目:MicroServiceDemo    文件:JwtTokenUtil.java   
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;
}
项目:Integrate    文件:JwtTokenUtil.java   
String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:single-sign-on-out-auth-jwt-cookie-redis-springboot-freemarker    文件:JwtUtil.java   
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;
}
项目:digag-server    文件:JwtTokenUtil.java   
private Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}
项目:digag-server    文件:JwtTokenUtil.java   
private String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:generator-spring-rest-jwt    文件:_JwtTokenUtil.java   
private Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}