/** * Copy constructor for access token. * * @param accessToken */ public DefaultOAuth2AccessToken(OAuth2AccessToken accessToken) { this(accessToken.getValue()); setAdditionalInformation(accessToken.getAdditionalInformation()); setRefreshToken(accessToken.getRefreshToken()); setExpiration(accessToken.getExpiration()); setScope(accessToken.getScope()); setTokenType(accessToken.getTokenType()); }
@RequestMapping(value = "/oauth/check_token") @ResponseBody public Map<String, ?> checkToken(@RequestParam("token") String value) { OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value); if (token == null) { throw new InvalidTokenException("Token was not recognised"); } if (token.isExpired()) { throw new InvalidTokenException("Token has expired"); } OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue()); Map<String, Object> response = (Map<String, Object>)accessTokenConverter.convertAccessToken(token, authentication); // gh-1070 response.put("active", true); // Always true if token exists and not expired return response; }
private OAuth2RefreshToken createRefreshToken(OAuth2AccessToken encodedRefreshToken) { if (!jwtTokenEnhancer.isRefreshToken(encodedRefreshToken)) { throw new InvalidTokenException("Encoded token is not a refresh token"); } if (encodedRefreshToken.getExpiration()!=null) { return new DefaultExpiringOAuth2RefreshToken(encodedRefreshToken.getValue(), encodedRefreshToken.getExpiration()); } return new DefaultOAuth2RefreshToken(encodedRefreshToken.getValue()); }
@Override public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest request) { OAuth2AccessToken accessToken = clientContext.getAccessToken(); if (accessToken == null) { throw new AccessTokenRequiredException(resource); } String tokenType = accessToken.getTokenType(); if (!StringUtils.hasText(tokenType)) { tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified. } else if (tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) { // gh-1346 tokenType = OAuth2AccessToken.BEARER_TYPE; // Ensure we use the correct syntax for the "Bearer" authentication scheme } request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue())); }
protected JaxbOAuth2AccessToken convertToInternal(OAuth2AccessToken accessToken) { JaxbOAuth2AccessToken jaxbAccessToken = new JaxbOAuth2AccessToken(); jaxbAccessToken.setAccessToken(accessToken.getValue()); jaxbAccessToken.setExpriation(accessToken.getExpiration()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); if(refreshToken != null) { jaxbAccessToken.setRefreshToken(refreshToken.getValue()); } return jaxbAccessToken; }
protected void verifyAccessTokens(OAuth2AccessToken oldAccessToken, OAuth2AccessToken newAccessToken) { // make sure the new access token can be used. verifyTokenResponse(newAccessToken.getValue(), HttpStatus.OK); // make sure the old access token isn't valid anymore. verifyTokenResponse(oldAccessToken.getValue(), HttpStatus.UNAUTHORIZED); }
/** * tests a happy-day flow of the refresh token provider. */ @Test public void testHappyDay() throws Exception { OAuth2AccessToken accessToken = getAccessToken("read write", "my-trusted-client"); // now use the refresh token to get a new access token. assertNotNull(accessToken.getRefreshToken()); OAuth2AccessToken newAccessToken = refreshAccessToken(accessToken.getRefreshToken().getValue()); assertFalse(newAccessToken.getValue().equals(accessToken.getValue())); verifyAccessTokens(accessToken, newAccessToken); cancelToken(accessToken.getValue()); cancelToken(newAccessToken.getValue()); }
byte[] serializedAccessToken = serialize(token); byte[] serializedAuth = serialize(authentication); byte[] accessKey = serializeKey(ACCESS + token.getValue()); byte[] authKey = serializeKey(AUTH + token.getValue()); byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication)); if (token.getExpiration() != null) { int seconds = token.getExpiresIn(); conn.expire(accessKey, seconds); conn.expire(authKey, seconds); conn.expire(approvalKey, seconds); OAuth2RefreshToken refreshToken = token.getRefreshToken(); if (refreshToken != null && refreshToken.getValue() != null) { byte[] refresh = serialize(token.getRefreshToken().getValue()); byte[] auth = serialize(token.getValue()); byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue()); byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue()); if (springDataRedis_2_0) { try {
public boolean revokeToken(String tokenValue) { OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); if (accessToken == null) { return false; } if (accessToken.getRefreshToken() != null) { tokenStore.removeRefreshToken(accessToken.getRefreshToken()); } tokenStore.removeAccessToken(accessToken); return true; }
@SuppressWarnings({"unchecked", "rawtypes"}) private void validateExternalAttributes(OAuth2AccessToken accessToken) { Map<String, String> extendedAttributes = (Map<String, String>) accessToken.getAdditionalInformation().get(ClaimConstants.EXTERNAL_ATTR); if (tokenEnhancer != null) { String atValue = accessToken.getValue().length() < 40 ? tokenSupport.tokens.get(accessToken.getValue()).getValue() : accessToken.getValue(); Map<String, Object> claims = JsonUtils.readValue(JwtHelper.decode(atValue).getClaims(), new TypeReference<Map<String, Object>>() { }); assertNotNull(claims.get("ext_attr")); assertEquals("test", ((Map) claims.get("ext_attr")).get("purpose")); assertNotNull(claims.get("ex_prop")); assertEquals("nz", ((Map) claims.get("ex_prop")).get("country")); assertThat((List<String>) claims.get("ex_groups"), containsInAnyOrder("admin", "editor")); } else { assertNull("External attributes should not exist", extendedAttributes); } }
OAuth2RefreshToken refreshToken = null; if (existingAccessToken != null) { if (existingAccessToken.isExpired()) { if (existingAccessToken.getRefreshToken() != null) { refreshToken = existingAccessToken.getRefreshToken(); tokenStore.storeAccessToken(accessToken, authentication); refreshToken = accessToken.getRefreshToken(); if (refreshToken != null) { tokenStore.storeRefreshToken(refreshToken, authentication);
if (token.getScope()!=null) { response.put(scopeAttribute, token.getScope()); if (token.getAdditionalInformation().containsKey(JTI)) { response.put(JTI, token.getAdditionalInformation().get(JTI)); if (token.getExpiration() != null) { response.put(EXP, token.getExpiration().getTime() / 1000); response.putAll(token.getAdditionalInformation());
@RequestMapping(value = "/fb/oauth/access_token") @ResponseBody public String accessToken(Principal principal, @RequestParam(value = "grant_type", defaultValue = "authorization_code") String grantType, @RequestParam Map<String, String> parameters) { tokenEndpoint.setAuthorizationRequestManager(authorizationRequestManager); tokenEndpoint.setClientDetailsService(clientDetailsService); tokenEndpoint.setProviderExceptionHandler(providerExceptionHandler); tokenEndpoint.setTokenGranter(tokenGranter); ResponseEntity<OAuth2AccessToken> accessToken = tokenEndpoint.getAccessToken(principal, grantType, parameters); return "access_token=" + accessToken.getBody().getValue() + "&expires=" + accessToken.getBody().getExpiresIn(); } }
claims.put(JTI, token.getAdditionalInformation().get(JTI)); claims.putAll(token.getAdditionalInformation()); claims.put(EXP, token.getExpiration().getTime() / 1000);
public boolean isRefreshToken(OAuth2AccessToken token) { return token.getAdditionalInformation().containsKey(ACCESS_TOKEN_ID); }
@Test public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); azParameters.put("authorities", "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}"); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken token = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(token, CLIENT_ID); assertThat(token, issuerUri(is(ISSUER_URI))); assertThat(token, scope(is(tokenSupport.requestedAuthScopes))); assertThat(token, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = token.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(token, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); Map<String, String> azMap = new LinkedHashMap<>(); azMap.put("external_group", "domain\\group1"); azMap.put("external_id", "abcd1234"); assertEquals(azMap, token.getAdditionalInformation().get("az_attr")); }
/** * Extract the implied approvals from any tokens associated with the user and client id supplied. * * @see org.springframework.security.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String, * java.lang.String) */ @Override public Collection<Approval> getApprovals(String userId, String clientId) { Collection<Approval> result = new HashSet<Approval>(); Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId); for (OAuth2AccessToken token : tokens) { OAuth2Authentication authentication = store.readAuthentication(token); if (authentication != null) { Date expiresAt = token.getExpiration(); for (String scope : token.getScope()) { result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED)); } } } return result; }
@Test @OAuth2ContextConfiguration(ResourceOwner.class) public void testTokenObtainedWithHeaderAuthentication() throws Exception { assertEquals(HttpStatus.OK, http.getStatusCode("/admin/beans")); int expiry = context.getAccessToken().getExpiresIn(); assertTrue("Expiry not overridden in config: " + expiry, expiry < 1000); assertEquals(new MediaType("application", "json", Charset.forName("UTF-8")), tokenEndpointResponse.getHeaders() .getContentType()); }
logger.debug("Existing access token=" + accessToken); if (accessToken != null && !accessToken.isExpired()) { if (logger.isDebugEnabled()) { logger.debug("User already approved with token=" + accessToken);
private TokenCacheObject(OAuth2AccessToken token, OAuth2Authentication auth) { this.token = token; this.auth = auth; // we don't need to check the cacheTokens values, because this won't actually be added to the cache if cacheTokens is false // if the token isn't null we use the token expire time // if forceCacheExpireTime is also true, we also make sure that the token expire time is shorter than the default expire time if ((this.token.getExpiration() != null) && (!forceCacheExpireTime || (forceCacheExpireTime && (this.token.getExpiration().getTime() - System.currentTimeMillis() <= defaultExpireTime)))) { this.cacheExpire = this.token.getExpiration(); } else { // if the token doesn't have an expire time, or if the using forceCacheExpireTime the token expire time is longer than the default, then use the default expire time Calendar cal = Calendar.getInstance(); cal.add(Calendar.MILLISECOND, defaultExpireTime); this.cacheExpire = cal.getTime(); } } }