Search in sources :

Example 31 with OAuth2Request

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

the class TokenStoreBaseTests method testRetrieveAccessToken.

@Test
public void testRetrieveAccessToken() {
    //Test approved request
    OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", true);
    OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test2", true));
    DefaultOAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
    expectedOAuth2AccessToken.setExpiration(new Date(Long.MAX_VALUE - 1));
    getTokenStore().storeAccessToken(expectedOAuth2AccessToken, authentication);
    //Test unapproved request
    storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false);
    authentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test2", true));
    OAuth2AccessToken actualOAuth2AccessToken = getTokenStore().getAccessToken(authentication);
    assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken);
    assertEquals(authentication.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()));
    actualOAuth2AccessToken = getTokenStore().getAccessToken(authentication);
    assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken);
    getTokenStore().removeAccessToken(expectedOAuth2AccessToken);
    assertNull(getTokenStore().readAccessToken("testToken"));
    assertNull(getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()));
    assertNull(getTokenStore().getAccessToken(authentication));
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) Test(org.junit.Test)

Example 32 with OAuth2Request

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

the class TokenStoreBaseTests method testGetAccessTokenForDeletedUser.

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

Example 33 with OAuth2Request

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

the class TokenEndpointAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication credentials = extractCredentials(request);
        if (credentials != null) {
            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }
            Authentication authResult = authenticationManager.authenticate(credentials);
            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }
            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException("No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            Map<String, String> map = getSingleValueMap(request);
            map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
            AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
            authorizationRequest.setScope(getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }
            OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
            SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
            onSuccessfulAuthentication(request, response, authResult);
        }
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }
        onUnsuccessfulAuthentication(request, response, failed);
        authenticationEntryPoint.commence(request, response, failed);
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 34 with OAuth2Request

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

the class TokenStoreUserApprovalHandler method checkForPreApproval.

@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    boolean approved = false;
    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();
    if (clientDetailsService != null) {
        try {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            approved = true;
            for (String scope : scopes) {
                if (!client.isAutoApprove(scope)) {
                    approved = false;
                }
            }
            if (approved) {
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }
    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);
    OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up existing token for ");
        builder.append("client_id=" + clientId);
        builder.append(", scope=" + scopes);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication);
    logger.debug("Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
        logger.debug("User already approved with token=" + accessToken);
        // A token was already granted and is still valid, so this is already approved
        approved = true;
    } else {
        logger.debug("Checking explicit approval");
        approved = userAuthentication.isAuthenticated() && approved;
    }
    authorizationRequest.setApproved(approved);
    return authorizationRequest;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException)

Example 35 with OAuth2Request

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

the class AuthorizationCodeTokenGranter 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);
    if (authorizationCode == null) {
        throw new InvalidRequestException("An authorization code must be supplied.");
    }
    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }
    OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();
    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the redirect_uri parameter
    String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
    if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }
    String pendingClientId = pendingOAuth2Request.getClientId();
    String clientId = tokenRequest.getClientId();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }
    // Secret is not required in the authorization request, so it won't be available
    // in the pendingAuthorizationRequest. We do want to check that a secret is provided
    // in the token request, but that happens elsewhere.
    Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request.getRequestParameters());
    // Combine the parameters adding the new ones last so they override if there are any clashes
    combinedParameters.putAll(parameters);
    // Make a new stored request with the combined parameters
    OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);
    Authentication userAuth = storedAuth.getUserAuthentication();
    return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) HashMap(java.util.HashMap) 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) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

Aggregations

OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)99 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)77 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.Test)56 HashMap (java.util.HashMap)21 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)16 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)15 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)14 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)13 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)12 Date (java.util.Date)11 HashSet (java.util.HashSet)11 Expression (org.springframework.expression.Expression)10 DBUnitTest (org.orcid.test.DBUnitTest)8 EvaluationContext (org.springframework.expression.EvaluationContext)8 MethodInvocation (org.aopalliance.intercept.MethodInvocation)7 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)7 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)7 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)7 SimpleMethodInvocation (org.springframework.security.util.SimpleMethodInvocation)7