Search in sources :

Example 66 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication 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 67 with OAuth2Authentication

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

the class OAuth2AuthenticationManager method checkClientDetails.

private void checkClientDetails(OAuth2Authentication auth) {
    if (clientDetailsService != null) {
        ClientDetails client;
        try {
            client = clientDetailsService.loadClientByClientId(auth.getOAuth2Request().getClientId());
        } catch (ClientRegistrationException e) {
            throw new OAuth2AccessDeniedException("Invalid token contains invalid client id");
        }
        Set<String> allowed = client.getScope();
        for (String scope : auth.getOAuth2Request().getScope()) {
            if (!allowed.contains(scope)) {
                throw new OAuth2AccessDeniedException("Invalid token contains disallowed scope (" + scope + ") for this client");
            }
        }
    }
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException)

Example 68 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication 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)

Example 69 with OAuth2Authentication

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

the class InMemoryTokenStore method removeAccessToken.

public void removeAccessToken(String tokenValue) {
    OAuth2AccessToken removed = this.accessTokenStore.remove(tokenValue);
    this.accessTokenToRefreshTokenStore.remove(tokenValue);
    // Don't remove the refresh token - it's up to the caller to do that
    OAuth2Authentication authentication = this.authenticationStore.remove(tokenValue);
    if (authentication != null) {
        this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication));
        Collection<OAuth2AccessToken> tokens;
        String clientId = authentication.getOAuth2Request().getClientId();
        tokens = this.userNameToAccessTokenStore.get(getApprovalKey(clientId, authentication.getName()));
        if (tokens != null) {
            tokens.remove(removed);
        }
        tokens = this.clientIdToAccessTokenStore.get(clientId);
        if (tokens != null) {
            tokens.remove(removed);
        }
        this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication));
    }
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 70 with OAuth2Authentication

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

the class JdbcTokenStore method getAccessToken.

public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    OAuth2AccessToken accessToken = null;
    String key = authenticationKeyGenerator.extractKey(authentication);
    try {
        accessToken = jdbcTemplate.queryForObject(selectAccessTokenFromAuthenticationSql, new RowMapper<OAuth2AccessToken>() {

            public OAuth2AccessToken mapRow(ResultSet rs, int rowNum) throws SQLException {
                return deserializeAccessToken(rs.getBytes(2));
            }
        }, key);
    } catch (EmptyResultDataAccessException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to find access token for authentication " + authentication);
        }
    } catch (IllegalArgumentException e) {
        LOG.error("Could not extract access token for authentication " + authentication, e);
    }
    if (accessToken != null && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
        removeAccessToken(accessToken.getValue());
        // Keep the store consistent (maybe the same user is represented by this authentication but the details have
        // changed)
        storeAccessToken(accessToken, authentication);
    }
    return accessToken;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) ResultSet(java.sql.ResultSet) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RowMapper(org.springframework.jdbc.core.RowMapper)

Aggregations

OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)167 Test (org.junit.Test)116 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)84 Authentication (org.springframework.security.core.Authentication)69 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)58 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)50 Date (java.util.Date)34 HashMap (java.util.HashMap)23 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)21 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)20 DBUnitTest (org.orcid.test.DBUnitTest)17 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)15 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)15 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)15 HashSet (java.util.HashSet)13 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)13 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)13 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)13 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)13 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)12