org.springframework.security.jwt.Jwt Java Examples
The following examples show how to use
org.springframework.security.jwt.Jwt.
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: MockUserManagementService.java From cloudbreak with Apache License 2.0 | 6 votes |
@Override public void verifyInteractiveUserSessionToken(VerifyInteractiveUserSessionTokenRequest request, StreamObserver<VerifyInteractiveUserSessionTokenResponse> responseObserver) { String sessionToken = request.getSessionToken(); Jwt token = decodeAndVerify(sessionToken, SIGNATURE_VERIFIER); AltusToken introspectResponse = jsonUtil.toObject(token.getClaims(), AltusToken.class); String userIdOrCrn = introspectResponse.getSub(); String[] splittedCrn = userIdOrCrn.split(":"); responseObserver.onNext( VerifyInteractiveUserSessionTokenResponse.newBuilder() .setAccountId(splittedCrn[4]) .setAccountType(AccountType.REGULAR) .setUserCrn(userIdOrCrn) .build()); responseObserver.onCompleted(); }
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: 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 #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: OAuthController.java From edison-microservice with Apache License 2.0 | 5 votes |
@RequestMapping( value = "/token", produces = "application/json", method = GET ) @ResponseBody public Jwt getTestToken() { return oAuthService.getExampleJWTToken(); }
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: 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 #13
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 #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: AuthService.java From JetfireCloud with Apache License 2.0 | 5 votes |
@Override public boolean invalidJwtAccessToken(String authentication) { verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey)); //是否无效true表示无效 boolean invalid = Boolean.TRUE; try { Jwt jwt = getJwt(authentication); jwt.verifySignature(verifier); invalid = Boolean.FALSE; } catch (InvalidSignatureException | IllegalArgumentException ex) { log.warn("user token has expired or signature error "); } return invalid; }
Example #16
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 #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: 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 #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: 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 #21
Source File: JwtUserService.java From springboot-vue.js-bbs with Apache License 2.0 | 4 votes |
public String getTokenUsername(String accessToken) { Jwt jwt = getParsedToken(accessToken); Map claim = JsonParserFactory.create().parseMap(jwt.getClaims()); return (String) claim.get("user_name"); }
Example #22
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 #23
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 #24
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 #25
Source File: IAuthService.java From JetfireCloud with Apache License 2.0 | 2 votes |
/** * 从认证信息中提取jwt token 对象 * * @param authentication 认证信息 Authorization: bearer header.payload.signature * @return Jwt对象 */ Jwt getJwt(String authentication);
Example #26
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()); }