io.jsonwebtoken.Jwts Java Examples

The following examples show how to use io.jsonwebtoken.Jwts. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TokenProvider.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: JwtService.java    From hauth-java with MIT License 6 votes vote down vote up
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();
}
 
Example #3
Source File: PeacefulController.java    From training with MIT License 6 votes vote down vote up
@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
}
 
Example #4
Source File: ApiTestUtils.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #5
Source File: AuthenticationProviderTokenTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: SmsVerificationJwtVerifier.java    From daming with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example #7
Source File: FederatedJwtAuthenticatorTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@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!");
}
 
Example #8
Source File: LoginTokenService.java    From smart-admin with MIT License 6 votes vote down vote up
/**
 * 功能描述: 生成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;
}
 
Example #9
Source File: JwtTokenGenerator.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: PersonController.java    From SpringBoot-Ignite with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: TokenAuthentication.java    From opscenter with Apache License 2.0 6 votes vote down vote up
/**
 * 根据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;
}
 
Example #12
Source File: MachineLoginFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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");
}
 
Example #13
Source File: OAuthFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@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!");
}
 
Example #14
Source File: JwtTokenUtil.java    From java-tutorial with MIT License 5 votes vote down vote up
/**
 * 从数据声明生成令牌
 *
 * @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();
}
 
Example #15
Source File: SSOClientTest.java    From sso-client with Apache License 2.0 5 votes vote down vote up
protected JwtBuilder jwtBuilder(long exp, Map<String, Object> ext){
    JwtBuilder jwt = Jwts.builder()
            .claim("user_id","43FE6476-CD7B-493B-8044-C7E3149D0876")
            .claim("scope","perm name user")
            .claim("client_id","console")
            .claim("username","admin");
    if(ext != null){
        for (Entry<String, Object> entry : ext.entrySet()){
            jwt.claim(entry.getKey(),entry.getValue());
        }
    }
    jwt.setExpiration(new Date(exp));
    return jwt;
}
 
Example #16
Source File: JwtUtil.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
/**
 * jwt 解密
 */
private static Claims buildClaims(String token, String jwtkey) {
	if (StringHelper.isBlank(token) || StringHelper.isBlank(jwtkey)) return null;

	String key = "";
	try {
		key = Base64.getEncoder().encodeToString(jwtkey.getBytes());
		Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
		return claims;
	} catch (Exception ex) {
		logger.error("用户TOKEN解析异常,token:{},key:{}", token, key);
	}
	return null;
}
 
Example #17
Source File: JwtTokenUtils.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * 生成token
 *
 * @param claim claim
 * @return token
 */
public static String createToken(Map<String, Object> claim) {
    LocalDateTime expireLocalDateTime = LocalDateTime.now().plus(adamProperties.getSecurity().getSignIn().getExpiration(), ChronoUnit.SECONDS);

    String jwtPrefix = adamProperties.getSecurity().getJwtToken().getPrefix();
    String jwtToken = Jwts.builder()
            .setClaims(claim)
            .setExpiration(DateUtils.localDateTimeToDate(expireLocalDateTime))
            .signWith(SignatureAlgorithm.HS512, adamProperties.getSecurity().getJwtToken().getSecret())
            .compact();
    return jwtPrefix + " " + jwtToken;
}
 
Example #18
Source File: JwtTokenUtil.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
/**
 * 根据负责生成JWT的token
 */
private String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
 
Example #19
Source File: TokenProviderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
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();
}
 
Example #20
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Override
public String getSubject(String token) {		
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
		       .parseClaimsJws(token).getBody();
	
	return claims.getSubject();
}
 
Example #21
Source File: JsonWebTokenUtility.java    From spring-boot-example with MIT License 5 votes vote down vote up
public void addToken(HttpServletResponse res, String userId){


        String JWT = Jwts.builder()
                        .setSubject(userId)
                        .setExpiration(new Date(System.currentTimeMillis() + config.getExpirationtime()))
                        .signWith(SignatureAlgorithm.HS512, config.getSecret())
                        .compact();
        res.addHeader(HEADER_NAME, JWT);
    }
 
Example #22
Source File: JwtTokenUtil.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
/**
 * 根据负责生成JWT的token
 */
private String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
 
Example #23
Source File: JwtUtil.java    From hellokoding-courses with MIT License 5 votes vote down vote up
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;
}
 
Example #24
Source File: JWTTokenGenerationServiceUnitTest.java    From SMSC with Apache License 2.0 5 votes vote down vote up
@Test
public void getUsernameFromTokenWithEmptyClaims() throws Exception {
    when(tokenGenerationService, method(JWTTokenGenerationServiceImpl.class, "getClaimsFromToken", String.class))
            .withArguments(anyString())
            .thenReturn(Jwts.claims());

    assertThat(tokenGenerationService.getUsernameFromToken(token)).isEqualTo(null);
}
 
Example #25
Source File: JwtTokenUtil.java    From spring-boot-vuejs-fullstack-examples with MIT License 5 votes vote down vote up
public String refreshToken(String token) {
  final Date createdDate = clock.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();
}
 
Example #26
Source File: JwtTokenService.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Validates and returns the claims of given JWS
 *
 * @param token compact JWS (JSON Web Signature)
 * @return {@link Claims} . Returns <code>null</code> if it fails to verify/expires the JWT.
 */
public @Nullable Claims getClaims(@Nonnull String token) {
  Claims claims;
  try {
    claims =
        Jwts.parser().setSigningKey(String.valueOf(secretKey)).parseClaimsJws(token).getBody();
  } catch (JwtException e) {
    log.debug("JWT token parser error.", e);
    claims = null;
  }
  return claims;
}
 
Example #27
Source File: JwtTokenUtil.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
/**
 * 根据负责生成JWT的token
 */
private String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
 
Example #28
Source File: AuthTokenUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime) {
    JwtBuilder builder = Jwts.builder()
            .setSubject(subject)
            .signWith(signingKey);

    expiryTime.ifPresent(builder::setExpiration);

    return builder.compact();
}
 
Example #29
Source File: JWTUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 创建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();
}
 
Example #30
Source File: ShiroJwtVerifyingFilter.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
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();
}