Java Code Examples for io.jsonwebtoken.Jwts#claims()

The following examples show how to use io.jsonwebtoken.Jwts#claims() . 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: JwtUtils.java    From mini-platform with MIT License 6 votes vote down vote up
/**
 * 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
 *
 * @param userName     = sub JWT面向的用户 (User)
 * @param clientId   = aud 接受JWT的一方 (Client)
 * @param expiration = exp  过期时间
 * @param issuedAt   = iat  签发时间
 * @return
 */
public static String createJavaWebToken(Long userId, String userName, String clientId, String scope,
                                        Date expiration, Date issuedAt) {

    Claims claims = Jwts.claims();
    claims.put(USER_ID_KEY, userId);
    claims.put(USER_NAME_KEY, userName);
    claims.put(CLIENT_ID_KEY, clientId);
    claims.put(SCOPE_KEY, scope);

    String token = Jwts.builder()
            .setClaims(claims)
            //JWT的签发者
            //.setIssuer("oauth")
            //.setSubject(userId)
            //.setAudience(clientId)
            .setExpiration(expiration)
            .setIssuedAt(issuedAt)
            .signWith(SignatureAlgorithm.HS256, getKeyInstance())
            .compact();
    return token;
}
 
Example 2
Source File: JwtClientServiceTest.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@Test(expected = MalformedJwtException.class)
public void should_throw_MalformedJwtException_whet_pass_token_without_expiration_and_type() throws Exception {
    // Create payload
    Long userId = RandomUtils.nextLong(10, 1000);
    Set<Integer> actions = new HashSet<>();
    actions.add(0);
    Set<String> networkIds = new HashSet<>();
    networkIds.add("string");
    Set<String> deviceTypeIds = new HashSet<>();
    deviceTypeIds.add("string");
    Set<String> deviceIds = new HashSet<>();
    deviceIds.add("string");
    JwtUserPayload.JwtUserPayloadBuilder jwtUserPayloadBuilder = new JwtUserPayload.JwtUserPayloadBuilder();
    JwtUserPayload payload = jwtUserPayloadBuilder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload();

    // Generate key without expiration date and token type
    Map<String, Object> jwtMap = new HashMap<>();
    jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, payload);
    Claims claims = Jwts.claims(jwtMap);
    String malformedToken = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret())
            .compact();
    jwtClientService.getUserPayload(malformedToken);
}
 
Example 3
Source File: JwtPluginTokenGenerator.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a JWT plugin 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 plugin token
 */
public String generateToken(JwtPluginPayload 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);

    JwtPluginPayload generatedPayload = (JwtPluginPayload) JwtPluginPayload.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 4
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 5
Source File: AuthoritiesImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that authorities are created correctly from claims found in a JWT.
 */
@Test
public void testFromClaims() {

    final Claims claims = Jwts.claims();
    claims.put("r:telemetry/*", "W");
    claims.put("r:registration/DEFAULT_TENANT", "RW");
    claims.put("o:credentials/*:get", "E");
    final Authorities auth = AuthoritiesImpl.from(claims);
    assertThat(auth.isAuthorized(ResourceIdentifier.fromString("telemetry/tenantA"), Activity.WRITE)).isTrue();
    assertThat(auth.isAuthorized(ResourceIdentifier.fromString("registration/DEFAULT_TENANT"), Activity.READ)).isTrue();
    assertThat(auth.isAuthorized(ResourceIdentifier.fromString("registration/tenantA"), Activity.READ)).isFalse();
    assertThat(auth.isAuthorized(ResourceIdentifier.fromString("credentials/DEFAULT_TENANT"), "get")).isTrue();
    assertThat(auth.isAuthorized(ResourceIdentifier.fromString("credentials/DEFAULT_TENANT"), "add")).isFalse();
}
 
Example 6
Source File: JwtTokenResourceTest.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@Test
public void should_return_401_after_providing_expired_refresh_token() throws Exception {
    // Create payload
    Long userId = ADMIN_ID;
    Set<String> actions = new HashSet<>();
    actions.add("string");
    Set<String> networkIds = new HashSet<>();
    networkIds.add("string");
    Set<String> deviceTypeIds = new HashSet<>();
    deviceTypeIds.add("string");
    JwtUserPayloadView.Builder builder = new JwtUserPayloadView.Builder();
    JwtUserPayloadView payload = builder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload();

    // Generate expired refresh token
    payload.setExpiration(new Date(System.currentTimeMillis() - 100));
    payload.setTokenType(TokenType.REFRESH);
    Map<String, Object> jwtMap = new HashMap<>();
    jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, payload.convertTo());
    Claims claims = Jwts.claims(jwtMap);
    String refreshToken = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret())
            .compact();

    JwtTokenVO tokenVO = new JwtTokenVO();
    tokenVO.setRefreshToken(refreshToken);

    JwtTokenVO jwtToken = performRequest("/token/refresh", "POST", emptyMap(), emptyMap(), tokenVO, UNAUTHORIZED, JwtTokenVO.class);
    Assert.assertNull(jwtToken.getAccessToken());
}
 
Example 7
Source File: AuthTokenBuilder.java    From production-ready-microservices-starter with MIT License 4 votes vote down vote up
/**
 * Creates access tokens from Authentication.
 *
 * @param authentication
 * @return token.
 */
public String createAccessToken(Authentication authentication) {

    String principal = (String) authentication.getPrincipal();

    if (StringUtils.isBlank(principal)) {
        throw new IllegalStateException("Authentication principle can not be null or empty.");
    }

    String[] orgTenantUsername = principal.split(String.valueOf(Character.LINE_SEPARATOR));

    if (orgTenantUsername == null || orgTenantUsername.length != 3) {
        throw new IllegalStateException(
                String.format("Authentication principle[%s] should contain org, tenant and username.", principal));
    }

    String org = orgTenantUsername[0];
    String tenant = orgTenantUsername[1];
    String username = orgTenantUsername[2];
    List<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());

    if (StringUtils.isBlank(org)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain org.", principal));
    }

    if (StringUtils.isBlank(tenant)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain tenant.", principal));
    }

    if (StringUtils.isBlank(username)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain username.", principal));
    }

    if (authorities == null || authorities.isEmpty()) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain authorities.", principal));
    }

    Claims claims = Jwts.claims();
    claims.setSubject(username);
    claims.put("org", org);
    claims.put("tenant", tenant);
    claims.put("scopes", authorities.stream().map(s -> s.toString()).collect(Collectors.toList()));

    LocalDateTime currentTime = dateUtil.getCurrentLocalDateTime();
    Date issueDate = Date.from(currentTime.toInstant(ZoneOffset.UTC));
    Date expiration = Date.from(currentTime.plusSeconds(
            authJwtProperties.getTokenExpirationTimeInSecond()).toInstant(ZoneOffset.UTC));

    PrivateKey privateKey = encryptionKeyUtil.loadPrivateKey(authJwtProperties.getTokenSigningPrivateKeyPath());

    return jwtUtil.getJwts(claims, authJwtProperties.getTokenIssuer(), issueDate, expiration, privateKey);
}
 
Example 8
Source File: JwtAuth.java    From liberty-bikes with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Obtain a JWT with the claims supplied. The key "id" will be used to set
 * the JWT subject.
 *
 * @param claims map of string->string for claim data to embed in the jwt.
 * @return jwt encoded as string, ready to send to http.
 */
protected String createJwt(Map<String, String> claims) throws IOException {
    if (signingKey == null) {
        getKeyStoreInfo();
    }

    Claims onwardsClaims = Jwts.claims();

    // Add all the remaining claims as-is.
    onwardsClaims.putAll(claims);

    // Set the subject using the "id" field from our claims map.
    onwardsClaims.setSubject(claims.get("id"));

    onwardsClaims.setId(claims.get("id"));

    // We'll use this claim to know this is a user token
    onwardsClaims.setAudience("client");

    onwardsClaims.setIssuer("https://libertybikes.mybluemix.net");
    // we set creation time to 24hrs ago, to avoid timezone issues in the
    // browser verification of the jwt.
    Calendar calendar1 = Calendar.getInstance();
    calendar1.add(Calendar.HOUR, -24);
    onwardsClaims.setIssuedAt(calendar1.getTime());

    // client JWT has 24 hrs validity from now.
    Calendar calendar2 = Calendar.getInstance();
    calendar2.add(Calendar.HOUR, 24);
    onwardsClaims.setExpiration(calendar2.getTime());

    // finally build the new jwt, using the claims we just built, signing it
    // with our signing key, and adding a key hint as kid to the encryption header,
    // which is optional, but can be used by the receivers of the jwt to know which
    // key they should verify it with.
    return Jwts.builder()
                    .setHeaderParam("kid", "bike")
                    .setHeaderParam("alg", "RS256")
                    .setClaims(onwardsClaims)
                    .signWith(SignatureAlgorithm.RS256, signingKey)
                    .compact();
}