Search in sources :

Example 51 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class DefaultAuthorizationRequestFactoryTests method testCreateTokenRequest.

@Test
public void testCreateTokenRequest() {
    TokenRequest request = factory.createTokenRequest(Collections.singletonMap("client_id", "foo"), client);
    assertEquals("foo", request.getClientId());
}
Also used : TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) Test(org.junit.Test)

Example 52 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class DefaultTokenServicesWithInMemoryTests method testExpiredRefreshToken.

@Test
public void testExpiredRefreshToken() throws Exception {
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false, Collections.singleton("read")), new TestAuthentication("test2", false));
    DefaultOAuth2AccessToken firstAccessToken = (DefaultOAuth2AccessToken) getTokenServices().createAccessToken(expectedAuthentication);
    assertNotNull(firstAccessToken.getRefreshToken());
    // Make it expire (and rely on mutable state in volatile token store)
    ReflectionTestUtils.setField(firstAccessToken.getRefreshToken(), "expiration", new Date(System.currentTimeMillis() - 1000));
    firstAccessToken.setExpiration(new Date(System.currentTimeMillis() - 1000));
    expected.expect(InvalidTokenException.class);
    expected.expectMessage("refresh token (expired)");
    TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", null, null);
    getTokenServices().refreshAccessToken(firstAccessToken.getRefreshToken().getValue(), tokenRequest);
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) Test(org.junit.Test)

Example 53 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class DefaultTokenServicesWithJwtTests method testDoubleRefresh.

@Test
public void testDoubleRefresh() throws Exception {
    JsonParser parser = JsonParserFactory.create();
    OAuth2Authentication authentication = createAuthentication();
    OAuth2AccessToken initialToken = getTokenServices().createAccessToken(authentication);
    TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", null, null);
    OAuth2AccessToken refreshedAccessToken = getTokenServices().refreshAccessToken(initialToken.getRefreshToken().getValue(), tokenRequest);
    refreshedAccessToken = getTokenServices().refreshAccessToken(refreshedAccessToken.getRefreshToken().getValue(), tokenRequest);
    Map<String, ?> accessTokenInfo = parser.parseMap(JwtHelper.decode(refreshedAccessToken.getValue()).getClaims());
    Map<String, ?> refreshTokenInfo = parser.parseMap(JwtHelper.decode(refreshedAccessToken.getRefreshToken().getValue()).getClaims());
    assertEquals("Access token ID does not match refresh token ATI", accessTokenInfo.get(AccessTokenConverter.JTI), refreshTokenInfo.get(AccessTokenConverter.ATI));
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) JsonParser(org.springframework.security.oauth2.common.util.JsonParser) Test(org.junit.Test)

Example 54 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.

the class OrcidAuthorizationCodeTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
    LOGGER.info("Getting OAuth2 authentication: code={}, redirectUri={}, clientId={}, scope={}", new Object[] { authorizationCode, redirectUri, tokenRequest.getClientId(), tokenRequest.getScope() });
    if (authorizationCode == null) {
        throw new OAuth2Exception("An authorization code must be supplied.");
    }
    //Validate the client is active
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(tokenRequest.getClientId());
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    //Validate scopes
    OrcidOauth2AuthoriziationCodeDetail codeDetails = orcidOauth2AuthoriziationCodeDetailDao.find(authorizationCode);
    if (codeDetails == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    } else {
        // Check auth code expiration
        Date tokenCreationDate = codeDetails.getDateCreated();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(tokenCreationDate);
        calendar.add(Calendar.MINUTE, authorizationCodeExpiration);
        Date tokenExpirationDate = calendar.getTime();
        if (tokenExpirationDate.before(new Date())) {
            throw new IllegalArgumentException("Authorization code has expired");
        }
        // Check granted scopes
        Set<String> grantedScopes = codeDetails.getScopes();
        Set<String> requestScopes = tokenRequest.getScope();
        for (String requestScope : requestScopes) {
            if (!grantedScopes.contains(requestScope)) {
                throw new InvalidScopeException("Invalid scopes: " + requestScope + " available scopes for this code are: " + grantedScopes);
            }
        }
    }
    //Consume code        
    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }
    OAuth2Request pendingAuthorizationRequest = storedAuth.getOAuth2Request();
    //Regenerate the authorization request but now with the request parameters
    pendingAuthorizationRequest = pendingAuthorizationRequest.createOAuth2Request(parameters);
    LOGGER.info("Found pending authorization request: redirectUri={}, clientId={}, scope={}, is_approved={}", new Object[] { pendingAuthorizationRequest.getRedirectUri(), pendingAuthorizationRequest.getClientId(), pendingAuthorizationRequest.getScope(), pendingAuthorizationRequest.isApproved() });
    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the
    // redirect_uri parameter
    String redirectUriApprovalParameter = pendingAuthorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
    if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }
    String pendingClientId = pendingAuthorizationRequest.getClientId();
    String clientId = client.getClientId();
    LOGGER.info("Comparing client ids: pendingClientId={}, authorizationRequest.clientId={}", pendingClientId, clientId);
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }
    Authentication userAuth = storedAuth.getUserAuthentication();
    return new OAuth2Authentication(pendingAuthorizationRequest, userAuth);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) Calendar(java.util.Calendar) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Date(java.util.Date) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Example 55 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.

the class OrcidClientCredentialsChecker method validateCredentials.

public OAuth2Request validateCredentials(String grantType, TokenRequest tokenRequest) {
    String clientId = tokenRequest.getClientId();
    String scopesString = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.SCOPE_PARAM);
    Set<String> scopes = new HashSet<String>();
    if (!PojoUtil.isEmpty(scopesString)) {
        scopes = OAuth2Utils.parseParameterList(scopesString);
    }
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    validateGrantType(grantType, clientDetails);
    if (scopes != null) {
        validateScope(clientDetails, scopes);
    }
    Map<String, String> authorizationParams = new HashMap<String, String>();
    authorizationParams.putAll(tokenRequest.getRequestParameters());
    authorizationParams.put(OrcidOauth2Constants.GRANT_TYPE, grantType);
    authorizationParams.put(OAuth2Utils.SCOPE, StringUtils.join(scopes, ' '));
    authorizationParams.put(OAuth2Utils.CLIENT_ID, clientId);
    AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(authorizationParams);
    authorizationRequest.setAuthorities(clientDetails.getAuthorities());
    authorizationRequest.setResourceIds(clientDetails.getResourceIds());
    authorizationRequest.setApproved(true);
    return oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)40 Test (org.junit.Test)38 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)34 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)33 Authentication (org.springframework.security.core.Authentication)25 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)21 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)13 HashMap (java.util.HashMap)11 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)11 ModelAndView (org.springframework.web.servlet.ModelAndView)10 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)9 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)9 RedirectView (org.springframework.web.servlet.view.RedirectView)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)7 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)7 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)5