Search in sources :

Example 86 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AbstractClientCredentialsProviderTests method testPostForTokenWithNoScopes.

/**
	 * tests that the registered scopes are used as defaults
	 */
@Test
@OAuth2ContextConfiguration(NoScopeClientCredentials.class)
public void testPostForTokenWithNoScopes() throws Exception {
    OAuth2AccessToken token = context.getAccessToken();
    assertFalse("Wrong scope: " + token.getScope(), token.getScope().isEmpty());
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 87 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AbstractRefreshTokenSupportTests method getAccessToken.

private OAuth2AccessToken getAccessToken(String scope, String clientId) throws Exception {
    MultiValueMap<String, String> formData = getTokenFormData(scope, clientId);
    HttpHeaders headers = getTokenHeaders(clientId);
    @SuppressWarnings("rawtypes") ResponseEntity<Map> response = http.postForMap(tokenPath(), headers, formData);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue("Wrong cache control: " + response.getHeaders().getFirst("Cache-Control"), response.getHeaders().getFirst("Cache-Control").contains("no-store"));
    @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
    return accessToken;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) MultiValueMap(org.springframework.util.MultiValueMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 88 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AbstractRefreshTokenSupportTests method testHappyDay.

/**
	 * 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);
}
Also used : DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Test(org.junit.Test)

Example 89 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project ORCID-Source by ORCID.

the class OpenIDController method getUserInfo.

/** Manually checks bearer token, looks up user or throws 403.
     * 
     * @return
     */
@RequestMapping(value = "/oauth/userinfo", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json")
@ResponseBody
public ResponseEntity<OpenIDConnectUserInfo> getUserInfo(HttpServletRequest request) {
    //note we do not support form post per https://tools.ietf.org/html/rfc6750 because it's a MAY and pointless
    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        //lookup token, check it's valid, check scope.
        String tokenValue = authHeader.replace("Bearer", "").trim();
        OAuth2AccessToken tok = tokenStore.readAccessToken(tokenValue);
        if (tok != null && !tok.isExpired()) {
            boolean hasScope = false;
            Set<ScopePathType> requestedScopes = ScopePathType.getScopesFromStrings(tok.getScope());
            for (ScopePathType scope : requestedScopes) {
                if (scope.hasScope(ScopePathType.OPENID)) {
                    hasScope = true;
                }
            }
            if (hasScope) {
                String orcid = tok.getAdditionalInformation().get("orcid").toString();
                Person person = personDetailsManagerReadOnly.getPublicPersonDetails(orcid);
                return ResponseEntity.ok(new OpenIDConnectUserInfo(orcid, person));
            }
        }
    }
    return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Also used : ScopePathType(org.orcid.jaxb.model.message.ScopePathType) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OpenIDConnectUserInfo(org.orcid.core.oauth.openid.OpenIDConnectUserInfo) Person(org.orcid.jaxb.model.record_v2.Person) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 90 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project ORCID-Source by ORCID.

the class OrcidClientCredentialEndPointDelegatorImpl method generateToken.

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code, String redirectUri, String grantType, String refreshToken, String state, String authorization, boolean revokeOld, Long expiresIn) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();
    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }
    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao.find(code);
        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }
            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE) || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
            //This will pass through to the token generator as a request param.
            if (authorizationCodeEntity.getNonce() != null) {
                authorizationParameters.put(OrcidOauth2Constants.NONCE, authorizationCodeEntity.getNonce());
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    //If it is a refresh token request, set the needed authorization parameters
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        authorizationParameters.put(OrcidOauth2Constants.AUTHORIZATION, authorization);
        authorizationParameters.put(OrcidOauth2Constants.REVOKE_OLD, String.valueOf(revokeOld));
        authorizationParameters.put(OrcidOauth2Constants.EXPIRES_IN, String.valueOf(expiresIn));
        authorizationParameters.put(OrcidOauth2Constants.REFRESH_TOKEN, String.valueOf(refreshToken));
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(authorizationParameters);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);
    //Need to change this to either the DefaultTokenType or start using a different token type.
    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object[] params = { grantType };
    if (token == null) {
        LOGGER.info("Unsupported grant type for OAuth2: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info("OAuth2 access token granted: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}, token={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri, token });
    return token;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)

Aggregations

OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)173 Test (org.junit.Test)126 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)112 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)66 Date (java.util.Date)36 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)31 Authentication (org.springframework.security.core.Authentication)27 HashMap (java.util.HashMap)22 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)19 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)18 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)18 DBUnitTest (org.orcid.test.DBUnitTest)17 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)17 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)16 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)11 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)10 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)10 Transactional (org.springframework.transaction.annotation.Transactional)10 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)9 ModelAndView (org.springframework.web.servlet.ModelAndView)9