Java Code Examples for org.springframework.security.jwt.JwtHelper

The following examples show how to use org.springframework.security.jwt.JwtHelper. These examples are extracted from open source projects. 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
/**
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

       // Get the Bearer Token and extract claims
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
       String accessToken = details.getTokenValue();
       String claims = JwtHelper.decode(accessToken).getClaims();
       
       // Extract user ID from Token claims -depending on Keycloak Identity Provider configuration
       // String userId = Spin.JSON(claims).prop("sub").stringValue();
       String userId = Spin.JSON(claims).prop("email").stringValue(); // useEmailAsCamundaUserId = true
       // String userId = Spin.JSON(claims).prop("preferred_username").stringValue(); // useUsernameAsCamundaUserId = true
       LOG.debug("Extracted userId from bearer token: {}", userId);

       try {
       	identityService.setAuthentication(userId, getUserGroups(userId));
       	chain.doFilter(request, response);
       } finally {
       	identityService.clearAuthentication();
       }
}
 
Example 2
public String getAccessToken() {
    if (accessToken == null) {
        retrieveNewAccessToken();
    }

    Jwt jwt = JwtHelper.decode(accessToken);
    String claims = jwt.getClaims();
    JsonParser jsonParser = JsonParserFactory.getJsonParser();
    Map<String, Object> claimMap = jsonParser.parseMap(claims);
    Integer exp = (Integer) claimMap.get("exp");
    int now = (int) (System.currentTimeMillis() / 1000L);

    if (exp < now) {
        retrieveNewAccessToken();
    }

    return accessToken;
}
 
Example 3
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("user", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0));
}
 
Example 4
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("admin", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0));
}
 
Example 5
Source Project: edison-microservice   Source File: OAuthService.java    License: Apache License 2.0 6 votes vote down vote up
public Jwt getExampleJWTToken() {
    final ZonedDateTime soon = ZonedDateTime.now().plusDays(365);
    final String jwtToken = "{\n" +
            "  \"aud\": [\n" +
            "    \"https://api.otto.de/api-authorization\"\n" +
            "  ],\n" +
            "  \"exp\": " + soon.toInstant().getEpochSecond() + ",\n" +
            "  \"user_name\": \"3d44bbc24614e28edd094bc54ef0497809717af5\",\n" +
            "  \"jti\": \"3cee521d-96a7-4d82-b726-7e02355f3a55\",\n" +
            "  \"client_id\": \"fe0661e5a99e4d43bd3496cc6c58025f\",\n" +
            "  \"scope\": [\n" +
            "    \"hello.read\"\n" +
            "  ]\n" +
            "}";
    final RsaSigner rsaSigner = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());

    return JwtHelper.encode(jwtToken, rsaSigner);
}
 
Example 6
Source Project: edison-microservice   Source File: OAuthTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public String getBearerToken(final String scope) {
    final ZonedDateTime soon = ZonedDateTime.now().plusDays(365);
    final String jwtToken = "{\n" +
            "  \"aud\": [\n" +
            "    \"" + aud + "\"\n" +
            "  ],\n" +
            "  \"exp\": " + soon.toEpochSecond() + ",\n" +
            "  \"user_name\": \"3d44bbc24614e28edd094bc54ef0497809717af5\",\n" +
            "  \"jti\": \"3cee521d-96a7-4d82-b726-7e02355f3a55\",\n" +
            "  \"client_id\": \"fe0661e5a99e4d43bd3496cc6c58025f\",\n" +
            "  \"scope\": [\n" +
            "    \"" + scope + "\"\n" +
            "  ]\n" +
            "}";
    final RsaSigner rsaSigner = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());
    final Jwt encode = JwtHelper.encode(jwtToken, rsaSigner);


    return "Bearer " + encode.getEncoded();
}
 
Example 7
Source Project: codeway_service   Source File: TestJwt.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
 public void testVerify(){
     //公钥
     String publickey ="-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnASXh9oSvLRLxk901HANYM6KcYMzX8vFPnH/To2R+SrUVw1O9rEX6m1+rIaMzrEKPm12qPjVq3HMXDbRdUaJEXsB7NgGrAhepYAdJnYMizdltLdGsbfyjITUCOvzZ/QgM1M4INPMD+Ce859xse06jnOkCUzinZmasxrmgNV3Db1GtpyHIiGVUY0lSO1Frr9m5dpemylaT0BV3UwTQWVW9ljm6yR3dBncOdDENumT5tGbaDVyClV0FEB1XdSKd7VjiDCDbUAUbDTG1fm3K9sx7kO1uMGElbXLgMfboJ963HEJcU01km7BmFntqI5liyKheX+HBUCD4zbYNPw236U+7QIDAQAB-----END PUBLIC KEY-----";
//jwt令牌
     String jwtString = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaXRjYXN0In0.lQOqL1s4DpDHROUAibkz6EMf6hcM7HmTPgmg-SlkacVoQAV7y3XQ7LXxiua6SJlN_uNX_EFjzIshEg_kyy972DtymtRMc2NIO5HzIF5I4oQCxNPsJdhu6qQni6sTas3q0JbAarMZSajDX7HhzVSYWPQJCussA4e1r9oFxDcoAo6TEAXOW8gRHzNIygQz1yCj6mdf4UOHI070kRy7f3BdhmrUJdOuDIMoRBYS4WsEOibAU1UCNPaJAXpZC0ihrtdY7SCg1N43fimeFOHrfpLb6OmRF7v7uvGMgrhg9JIYDbJ6nbode5OJkNceRx8QUICre2yKAe0ctlvXO0REf6OpRA";
     //校验jwt令牌
     Jwt jwt = JwtHelper.decodeAndVerify(jwtString, new RsaVerifier(publickey));

     //拿到jwt令牌中自定义的内容
     String claims = jwt.getClaims();
     System.out.println(claims);
 }
 
Example 8
public static boolean invalidJwtAccessToken(String authentication) {
	//verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey));
	//是否无效true表示无效
	boolean invalid = Boolean.TRUE;
	try {
		String pubKey = JWTAuthentication.getPubKey(PUBLIC_KEY);
		RsaVerifier rsaVerifier = new RsaVerifier(pubKey);
		Jwt jwt = JwtHelper.decode(authentication);
		jwt.verifySignature(rsaVerifier);
		invalid = Boolean.FALSE;
	} catch (InvalidSignatureException | IllegalArgumentException ex) {
		LogBack.error("user token has expired or signature error");
	}
	return invalid;
}
 
Example 9
Source Project: spring-microservice-exam   Source File: CustomTokenConverter.java    License: MIT License 5 votes vote down vote up
@Override
protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
	String content;
	try {
		content = this.objectMapper
				.formatMap(getAccessTokenConverter().convertAccessToken(accessToken, authentication));
	} catch (Exception ex) {
		throw new IllegalStateException("Cannot convert access token to JSON", ex);
	}
	return JwtHelper.encode(content, this.signer, this.customHeaders).getEncoded();
}
 
Example 10
Source Project: cubeai   Source File: OAuth2CookieHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the given claim from the given token.
 *
 * @param refreshToken the JWT token to examine.
 * @param claimName    name of the claim to get.
 * @param clazz        the Class we expect to find there.
 * @return the desired claim.
 * @throws InvalidTokenException if we cannot find the claim in the token or it is of wrong type.
 */
@SuppressWarnings("unchecked")
private <T> T getClaim(String refreshToken, String claimName, Class<T> clazz) {
    Jwt jwt = JwtHelper.decode(refreshToken);
    String claims = jwt.getClaims();
    Map<String, Object> claimsMap = jsonParser.parseMap(claims);
    Object claimValue = claimsMap.get(claimName);
    if (claimValue == null) {
        return null;
    }
    if (!clazz.isAssignableFrom(claimValue.getClass())) {
        throw new InvalidTokenException("claim is not of expected type: " + claimName);
    }
    return (T) claimValue;
}
 
Example 11
Source Project: codeway_service   Source File: TestJwt.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
 public void testVerify(){
     //公钥
     String publickey ="-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnASXh9oSvLRLxk901HANYM6KcYMzX8vFPnH/To2R+SrUVw1O9rEX6m1+rIaMzrEKPm12qPjVq3HMXDbRdUaJEXsB7NgGrAhepYAdJnYMizdltLdGsbfyjITUCOvzZ/QgM1M4INPMD+Ce859xse06jnOkCUzinZmasxrmgNV3Db1GtpyHIiGVUY0lSO1Frr9m5dpemylaT0BV3UwTQWVW9ljm6yR3dBncOdDENumT5tGbaDVyClV0FEB1XdSKd7VjiDCDbUAUbDTG1fm3K9sx7kO1uMGElbXLgMfboJ963HEJcU01km7BmFntqI5liyKheX+HBUCD4zbYNPw236U+7QIDAQAB-----END PUBLIC KEY-----";
//jwt令牌
     String jwtString = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaXRjYXN0In0.lQOqL1s4DpDHROUAibkz6EMf6hcM7HmTPgmg-SlkacVoQAV7y3XQ7LXxiua6SJlN_uNX_EFjzIshEg_kyy972DtymtRMc2NIO5HzIF5I4oQCxNPsJdhu6qQni6sTas3q0JbAarMZSajDX7HhzVSYWPQJCussA4e1r9oFxDcoAo6TEAXOW8gRHzNIygQz1yCj6mdf4UOHI070kRy7f3BdhmrUJdOuDIMoRBYS4WsEOibAU1UCNPaJAXpZC0ihrtdY7SCg1N43fimeFOHrfpLb6OmRF7v7uvGMgrhg9JIYDbJ6nbode5OJkNceRx8QUICre2yKAe0ctlvXO0REf6OpRA";
     //校验jwt令牌
     Jwt jwt = JwtHelper.decodeAndVerify(jwtString, new RsaVerifier(publickey));

     //拿到jwt令牌中自定义的内容
     String claims = jwt.getClaims();
     System.out.println(claims);
 }
 
Example 12
public static boolean invalidJwtAccessToken(String authentication) {
	//verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey));
	//是否无效true表示无效
	boolean invalid = Boolean.TRUE;
	try {
		String pubKey = JWTAuthentication.getPubKey(PUBLIC_KEY);
		RsaVerifier rsaVerifier = new RsaVerifier(pubKey);
		Jwt jwt = JwtHelper.decode(authentication);
		jwt.verifySignature(rsaVerifier);
		invalid = Boolean.FALSE;
	} catch (InvalidSignatureException | IllegalArgumentException ex) {
		LogBack.error("user token has expired or signature error");
	}
	return invalid;
}
 
Example 13
Source Project: gateway-helper   Source File: AddJwtFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean run(RequestContext context) {
    try {
        String token = objectMapper.writeValueAsString(context.getCustomUserDetails());
        String jwt = "Bearer " + JwtHelper.encode(token, jwtSigner).getEncoded();
        context.response.setJwt(jwt);
        return true;
    } catch (JsonProcessingException e) {
        context.response.setStatus(CheckState.EXCEPTION_GATEWAY_HELPER);
        context.response.setMessage("gateway helper error happened: " + e.toString());
        return false;
    }
}
 
Example 14
Source Project: api-gateway-old   Source File: AddJwtFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean run(RequestContext context) {
    try {
        String token = objectMapper.writeValueAsString(context.getCustomUserDetails());
        String jwt = "Bearer " + JwtHelper.encode(token, jwtSigner).getEncoded();
        context.response.setJwt(jwt);
        return true;
    } catch (JsonProcessingException e) {
        context.response.setStatus(CheckState.EXCEPTION_GATEWAY_HELPER);
        context.response.setMessage("gateway helper error happened: " + e.toString());
        return false;
    }
}
 
Example 15
@Test
public void tokenWhenUsingClientCredentialsThenIsValid() throws Exception {
	MvcResult result = this.mvc.perform(post("/oauth/token").with(CLIENT_CREDENTIALS)
			.param("grant_type", "client_credentials").param("scope", "any")).andExpect(status().isOk())
			.andReturn();

	String accessToken = extract(result, "access_token");

	JwtHelper.decodeAndVerify(accessToken, new RsaVerifier(privateKeyValue));
}
 
Example 16
Source Project: OAuth-2.0-Cookbook   Source File: Claims.java    License: MIT License 5 votes vote down vote up
public static Claims createFrom(ObjectMapper jsonMapper, OAuth2AccessToken accessToken) {
    try {
        String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
        Jwt decodedToken = JwtHelper.decode(idToken);
        return jsonMapper.readValue(decodedToken.getClaims(), Claims.class);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source Project: OAuth-2.0-Cookbook   Source File: Claims.java    License: MIT License 5 votes vote down vote up
public static Claims createFrom(ObjectMapper jsonMapper, OAuth2AccessToken accessToken) {
    try {
        String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
        Jwt decodedToken = JwtHelper.decode(idToken);
        return jsonMapper.readValue(decodedToken.getClaims(), Claims.class);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByTrustedClient() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);

    String claims = jwtToken.getClaims();
    logJson(claims);

    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    List<String> authorities = (List<String>) claimsMap.get("authorities");
    assertEquals(1, authorities.size());
    assertEquals("ROLE_TRUSTED_CLIENT", authorities.get(0));
}
 
Example 19
Source Project: multiapps-controller   Source File: JwtTokenParser.java    License: Apache License 2.0 5 votes vote down vote up
private void decodeAndVerify(String tokenString) {
    try {
        JwtHelper.decodeAndVerify(tokenString, getSignatureVerifier(getCachedTokenKey()));
    } catch (InvalidSignatureException e) {
        throw new InvalidTokenException(e.getMessage(), e);
    }
}
 
Example 20
private static OAuthToken parseJwtToken(String jwtToken) {
    try {
        Jwt jwt = JwtHelper.decode(jwtToken);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(jwt.getClaims().getBytes(), OAuthToken.class);
    } catch (IOException e) {
        throw new AuthenticationException("Invalid OAuth2 Token", e);
    }
}
 
Example 21
@Override
protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    String content;
    try {
        content = this.objectMapper.formatMap(getAccessTokenConverter().convertAccessToken(accessToken, authentication));
    } catch (Exception ex) {
        throw new IllegalStateException("Cannot convert access token to JSON", ex);
    }
    String token = JwtHelper.encode(content, this.signer, this.customHeaders)
        .getEncoded();
    return token;
}
 
Example 22
private Map<String, Object> decodeJwtMap(final String token, final OAuthPublicKey keyExchangePublicKey) {
    final RsaVerifier rsaVerifier = new RsaVerifier(keyExchangePublicKey.getPublicKey());
    final Jwt jwt = JwtHelper.decodeAndVerify(token, rsaVerifier);

    final String content = jwt.getClaims();

    final Map<String, Object> map = objectMapper.parseMap(content);
    if (map.containsKey(EXP) && map.get(EXP) instanceof Integer) {
        final Integer intValue = (Integer) map.get(EXP);
        map.put(EXP, Long.valueOf(intValue));
    }
    return map;
}
 
Example 23
Source Project: tutorials   Source File: OAuth2CookieHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieve the given claim from the given token.
 *
 * @param refreshToken the JWT token to examine.
 * @param claimName    name of the claim to get.
 * @param clazz        the Class we expect to find there.
 * @return the desired claim.
 * @throws InvalidTokenException if we cannot find the claim in the token or it is of wrong type.
 */
@SuppressWarnings("unchecked")
private <T> T getClaim(String refreshToken, String claimName, Class<T> clazz) {
    Jwt jwt = JwtHelper.decode(refreshToken);
    String claims = jwt.getClaims();
    Map<String, Object> claimsMap = jsonParser.parseMap(claims);
    Object claimValue = claimsMap.get(claimName);
    if (claimValue == null) {
        return null;
    }
    if (!clazz.isAssignableFrom(claimValue.getClass())) {
        throw new InvalidTokenException("claim is not of expected type: " + claimName);
    }
    return (T) claimValue;
}
 
Example 24
Source Project: codeway_service   Source File: AuthService.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Jwt getJwt(String authentication) {
    return JwtHelper.decode(authentication);
}
 
Example 25
Source Project: codeway_service   Source File: AuthService.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Jwt getJwt(String authentication) {
    return JwtHelper.decode(authentication);
}
 
Example 26
Source Project: JetfireCloud   Source File: AuthService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Jwt getJwt(String authentication) {
    return JwtHelper.decode(StringUtils.substring(authentication, BEARER_BEGIN_INDEX));
}
 
Example 27
Source Project: springboot-vue.js-bbs   Source File: JwtUserService.java    License: Apache License 2.0 4 votes vote down vote up
private Jwt getParsedToken(String accessToken) {
    return JwtHelper.decode(accessToken.split(" ")[1]);
}
 
Example 28
private static String signAndEncodeToken(String claims, Map<String, String> tokenHeaders) {
	RsaSigner signer = new RsaSigner(readPrivateKeyFromFile());

	org.springframework.security.jwt.Jwt jwt = JwtHelper.encode(claims, signer, tokenHeaders);

	return jwt.getEncoded();
}
 
Example 29
Source Project: microservices-platform   Source File: JwtUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
 * @param jwtToken token值
 * @param rsaPublicKey 公钥
 * @return
 */
public static JSONObject decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) {
    SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
    Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
    return JSONObject.parseObject(jwt.getClaims());
}