List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getValue
String getValue();
From source file:org.apigw.authserver.web.controller.CertifiedClientsController.java
@RequestMapping(value = "/oauth/revoke", method = RequestMethod.POST) public String revokeAuthorization(@RequestParam("grantId") long grantId) { log.debug("revokeAuthorization"); UserDetails user = getUserDetailsFromSecurityContext(); Collection<OAuth2AccessToken> tokens = getAccessTokens(user.getUsername()); String tokenValue = null;/* w w w . ja v a 2s . com*/ for (OAuth2AccessToken t : tokens) { Map<String, Object> additionalInformation = t.getAdditionalInformation(); long id = (Long) additionalInformation.get("authorization_grant_id"); if (grantId == id) { tokenValue = t.getValue(); break; } } if (tokenValue == null) { throw new RuntimeException("No token found for grantId=" + grantId); //TODO: throw something better? } try { consumerTokenServices.revokeToken(tokenValue); } catch (RuntimeException e) { log.error("Caught exception while trying to revoke token", e); throw (e); } log.debug("returning from revokeAuthorization"); return "redirect:/oauth/clients"; }
From source file:com.iflytek.edu.cloud.frame.spring.RedisTokenStore.java
@Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { String refreshToken = null;/*from ww w.j a v a 2 s .c om*/ if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } if (readAccessToken(token.getValue()) != null) { removeAccessToken(token.getValue()); } String tokenKey = extractTokenKey(token.getValue()); Jedis jedis = jedisPool.getResource(); try { if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } if (readAccessToken(token.getValue()) != null) { removeAccessToken(token.getValue()); } jedis.hset(ACCESS_TOKEN_KEY, toBytes(tokenKey), serializeAccessToken(token)); jedis.hset(ACCESS_TOKEN_AUTH_KEY, toBytes(tokenKey), serializeAuthentication(authentication)); jedis.hset(ACCESS_REFRESH_CODE_KEY, toBytes(refreshToken), toBytes(token.getValue())); jedis.hset(ACCESS_AUTH_ID_KEY, toBytes(authenticationKeyGenerator.extractKey(authentication)), toBytes(token.getValue())); } finally { jedisPool.returnResource(jedis); } }
From source file:com.cedac.security.oauth2.provider.token.store.TokenStoreBaseTests.java
@Test public void testGetAccessTokenForDeletedUser() throws Exception { //Test approved request OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", true); OAuth2Authentication expectedAuthentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test", true)); OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken"); getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication); assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(expectedAuthentication)); assertEquals(expectedAuthentication, getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue())); //Test unapproved request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false); OAuth2Authentication anotherAuthentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test", true)); assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(anotherAuthentication)); // The generated key for the authentication is the same as before, but the two auths are not equal. This could // happen if there are 2 users in a system with the same username, or (more likely), if a user account was // deleted and re-created. assertEquals(anotherAuthentication.getUserAuthentication(), getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getUserAuthentication()); // The authorizationRequest does not match because it is unapproved, but the token was granted to an approved request assertFalse(storedOAuth2Request.equals( getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getOAuth2Request())); }
From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java
@Transactional(isolation = Isolation.SERIALIZABLE) public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { OAuth2AccessToken existingAccessToken = localtokenStore.getAccessToken(authentication); OAuth2RefreshToken refreshToken = null; if (existingAccessToken != null) { if (existingAccessToken.isExpired()) { if (existingAccessToken.getRefreshToken() != null) { refreshToken = existingAccessToken.getRefreshToken(); // The token store could remove the refresh token when the access token is removed, but we want to // be sure... localtokenStore.removeRefreshToken(refreshToken); }/*from w w w. j ava2 s. c o m*/ localtokenStore.removeAccessToken(existingAccessToken); } else { return tokenEnhancer != null ? tokenEnhancer.enhance(existingAccessToken, authentication) : existingAccessToken; } } // Only create a new refresh token if there wasn't an existing one associated with an expired access token. // Clients might be holding existing refresh tokens, so we re-use it in the case that the old access token // expired. if (refreshToken == null) { refreshToken = createRefreshToken(authentication); } // But the refresh token itself might need to be re-issued if it has expired. else if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken; if (isExpired(expiring)) { refreshToken = createRefreshToken(authentication); } } OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); localtokenStore.storeAccessToken(accessToken, authentication); if (refreshToken != null) { localtokenStore.storeRefreshToken(refreshToken, authentication); } traceUserLogger.info(String.format("'type':'new','user':'%s','token':'%s'", authentication.getName(), accessToken.getValue())); return accessToken; }
From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) { Map<String, Object> vars = new LinkedHashMap<>(); Map<String, String> keys = new HashMap<>(); if (isNull(accessToken)) { throw new InvalidRequestException("An implicit grant could not be made"); }/*from w w w .j ava 2s . co m*/ vars.put("access_token", accessToken.getValue()); vars.put("token_type", accessToken.getTokenType()); String state = authorizationRequest.getState(); if (nonNull(state)) { vars.put("state", state); } Date expiration = accessToken.getExpiration(); if (nonNull(expiration)) { long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000; vars.put("expires_in", expires_in); } String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE); if (isNull(originalScope) || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) { vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope())); } Map<String, Object> additionalInformation = accessToken.getAdditionalInformation(); for (String key : additionalInformation.keySet()) { Object value = additionalInformation.get(key); if (nonNull(value)) { keys.put("extra_" + key, key); vars.put("extra_" + key, value); } } // Do not include the refresh token (even if there is one) return append(authorizationRequest.getRedirectUri(), vars, keys, true); }
From source file:org.eclipse.cft.server.core.internal.client.CFClientV1Support.java
protected AuthorizationHeaderProvider getHeaderProvider(final CloudFoundryOperations cfClient) { AuthorizationHeaderProvider oauth = new AuthorizationHeaderProvider() { public String getAuthorizationHeader() { OAuth2AccessToken token = cfClient.login(); if (cfServer != null) { // In the SSO case, store the token for later use try { String tokenValue = CloudUtil.getTokenAsJson(token); cfServer.setAndSaveToken(tokenValue); } catch (JsonProcessingException e) { CloudFoundryPlugin.logWarning(e.getMessage()); }// w w w . j ava 2 s . c o m } return token.getTokenType() + " " + token.getValue(); //$NON-NLS-1$ } }; return oauth; }
From source file:com.bcknds.demo.oauth2.security.PasswordAuthenticationTests.java
/** * Verify that authentication is successful. *//*from w w w . ja v a2 s. c o m*/ @Test public void testSuccessfulAuthentication() { OAuth2RestTemplate restTemplate = AuthenticationUtil.getPasswordCredentials(USERNAME, PASSWORD); OAuth2AccessToken token = null; try { token = restTemplate.getAccessToken(); } catch (OAuth2AccessDeniedException ex) { if (ex.getCause() instanceof ResourceAccessException) { fail("It appears that the server may not be running. Please start it before running tests"); } else { fail(ex.getMessage()); } } catch (Exception ex) { fail(ex.getMessage()); } assertNotNull(token.getValue()); }
From source file:com.companyname.filters.Oauth2ReAuthenticationFilter.java
private String refreshAccesTokenIfExpired(String accessTokenValue, Authentication authentication) { OAuth2AccessToken accessToken = getTokenService().readAccessToken(accessTokenValue); if (accessToken != null && accessToken.isExpired() && authentication != null) { logger.info("access token is expired. will refresh"); accessToken = getTokenService().createAccessToken((OAuth2Authentication) authentication); } else if (accessToken != null && !accessToken.isExpired()) { logger.info("access token is not expired"); }/*from w ww . j a va 2 s. c om*/ return (accessToken == null) ? null : accessToken.getValue(); }
From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientV1.java
public String login() { if (cloudCredentials.getEmail() == null) { Assert.hasLength(cloudCredentials.getToken(), "No authentication details provided"); token = cloudCredentials.getToken(); return token; }//from w w w .ja va 2 s . c o m Assert.hasLength(cloudCredentials.getEmail(), "Email cannot be null or empty"); Assert.hasLength(cloudCredentials.getPassword(), "Password cannot be null or empty"); if (oauthClient != null) { OAuth2AccessToken token = oauthClient.getToken(cloudCredentials.getEmail(), cloudCredentials.getPassword()); this.token = token.getTokenType() + " " + token.getValue(); return this.token; } else { Map<String, String> payload = new HashMap<String, String>(); payload.put("password", cloudCredentials.getPassword()); Map<String, String> response = getRestTemplate().postForObject(getUrl("users/{id}/tokens"), payload, Map.class, cloudCredentials.getEmail()); token = response.get("token"); return token; } }
From source file:oauth2.authentication.tokens.TokenServiceImpl.java
@Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { String key = authenticationKeyGenerator.extractKey(authentication); AccessToken oldEntity = accessTokenRepository.findByAuthenticationId(key); if (oldEntity != null) { accessTokenRepository.delete(oldEntity); }/* w ww . j a v a 2 s . com*/ String refreshToken = null; if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } AccessToken entity = new AccessToken(); entity.setTokenId(extractTokenKey(token.getValue())); entity.setToken(token); entity.setAuthenticationId(key); entity.setUserId(authentication.isClientOnly() ? null : authentication.getName()); entity.setClientId(authentication.getOAuth2Request().getClientId()); entity.setAuthentication(authentication); entity.setRefreshToken(extractTokenKey(refreshToken)); accessTokenRepository.save(entity); }