org.springframework.security.jwt.JwtHelper Java Examples
The following examples show how to use
org.springframework.security.jwt.JwtHelper.
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: KeycloakAuthenticationFilter.java From camunda-bpm-identity-keycloak with Apache License 2.0 | 6 votes |
/** * {@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
Source File: OAuth2ClientCredentialsService.java From flair-registry with Apache License 2.0 | 6 votes |
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
Source File: OAuthTestHelper.java From edison-microservice with Apache License 2.0 | 6 votes |
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 #4
Source File: OAuthService.java From edison-microservice with Apache License 2.0 | 6 votes |
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 #5
Source File: GrantByResourceOwnerPasswordCredentialTest.java From demo-spring-boot-security-oauth2 with MIT License | 6 votes |
@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 #6
Source File: GrantByResourceOwnerPasswordCredentialTest.java From demo-spring-boot-security-oauth2 with MIT License | 6 votes |
@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 #7
Source File: AddJwtFilter.java From api-gateway-old with Apache License 2.0 | 5 votes |
@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 #8
Source File: OAuth2CookieHelper.java From tutorials with MIT License | 5 votes |
/** * 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 #9
Source File: KeyExchangeJwtAccessTokenConverter.java From edison-microservice with Apache License 2.0 | 5 votes |
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 #10
Source File: JwtCustomHeadersAccessTokenConverter.java From spring-security-oauth with MIT License | 5 votes |
@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 #11
Source File: OAuthTokenUtil.java From careconnect-reference-implementation with Apache License 2.0 | 5 votes |
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 #12
Source File: JwtTokenParser.java From multiapps-controller with Apache License 2.0 | 5 votes |
private void decodeAndVerify(String tokenString) { try { JwtHelper.decodeAndVerify(tokenString, getSignatureVerifier(getCachedTokenKey())); } catch (InvalidSignatureException e) { throw new InvalidTokenException(e.getMessage(), e); } }
Example #13
Source File: GrantByClientCredentialTest.java From demo-spring-boot-security-oauth2 with MIT License | 5 votes |
@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 #14
Source File: Claims.java From OAuth-2.0-Cookbook with MIT License | 5 votes |
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 #15
Source File: Claims.java From OAuth-2.0-Cookbook with MIT License | 5 votes |
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 #16
Source File: SampleSecureOAuth2ApplicationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 5 votes |
@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 #17
Source File: TestJwt.java From codeway_service with GNU General Public License v3.0 | 5 votes |
@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 #18
Source File: AddJwtFilter.java From gateway-helper with Apache License 2.0 | 5 votes |
@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 #19
Source File: JWTAuthentication.java From codeway_service with GNU General Public License v3.0 | 5 votes |
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 #20
Source File: TestJwt.java From codeway_service with GNU General Public License v3.0 | 5 votes |
@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 #21
Source File: OAuth2CookieHelper.java From cubeai with Apache License 2.0 | 5 votes |
/** * 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 #22
Source File: CustomTokenConverter.java From spring-microservice-exam with MIT License | 5 votes |
@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 #23
Source File: JWTAuthentication.java From codeway_service with GNU General Public License v3.0 | 5 votes |
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 #24
Source File: AuthService.java From JetfireCloud with Apache License 2.0 | 4 votes |
@Override public Jwt getJwt(String authentication) { return JwtHelper.decode(StringUtils.substring(authentication, BEARER_BEGIN_INDEX)); }
Example #25
Source File: AuthService.java From codeway_service with GNU General Public License v3.0 | 4 votes |
public Jwt getJwt(String authentication) { return JwtHelper.decode(authentication); }
Example #26
Source File: JwtUserService.java From springboot-vue.js-bbs with Apache License 2.0 | 4 votes |
private Jwt getParsedToken(String accessToken) { return JwtHelper.decode(accessToken.split(" ")[1]); }
Example #27
Source File: AuthService.java From codeway_service with GNU General Public License v3.0 | 4 votes |
public Jwt getJwt(String authentication) { return JwtHelper.decode(authentication); }
Example #28
Source File: JwtGenerator.java From cloud-security-xsuaa-integration with Apache License 2.0 | 3 votes |
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 File: JwtUtils.java From microservices-platform with Apache License 2.0 | 2 votes |
/** * {"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()); }