Search in sources :

Example 1 with InvalidGrantException

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

the class TokenEndpoint method postAccessToken.

@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
    }
    String clientId = getClientId(principal);
    ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
    if (clientId != null && !clientId.equals("")) {
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }
    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }
    if (!StringUtils.hasText(tokenRequest.getGrantType())) {
        throw new InvalidRequestException("Missing grant type");
    }
    if (tokenRequest.getGrantType().equals("implicit")) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }
    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            logger.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }
    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }
    OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
    }
    return getResponse(token);
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with InvalidGrantException

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

the class DefaultRedirectResolver method resolveRedirect.

public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception {
    Set<String> authorizedGrantTypes = client.getAuthorizedGrantTypes();
    if (authorizedGrantTypes.isEmpty()) {
        throw new InvalidGrantException("A client must have at least one authorized grant type.");
    }
    if (!containsRedirectGrantType(authorizedGrantTypes)) {
        throw new InvalidGrantException("A redirect_uri can only be used by implicit or authorization_code grant types.");
    }
    Set<String> redirectUris = client.getRegisteredRedirectUri();
    if (redirectUris != null && !redirectUris.isEmpty()) {
        return obtainMatchingRedirect(redirectUris, requestedRedirect);
    } else if (StringUtils.hasText(requestedRedirect)) {
        return requestedRedirect;
    } else {
        throw new InvalidRequestException("A redirect_uri must be supplied.");
    }
}
Also used : InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

Example 3 with InvalidGrantException

use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException 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 4 with InvalidGrantException

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

the class DefaultTokenServices method refreshAccessToken.

@Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class })
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    if (!supportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
    if (refreshToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
    if (this.authenticationManager != null && !authentication.isClientOnly()) {
        // The client has already been authenticated, but the user authentication might be old now, so give it a
        // chance to re-authenticate.
        Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
        user = authenticationManager.authenticate(user);
        Object details = authentication.getDetails();
        authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
        authentication.setDetails(details);
    }
    String clientId = authentication.getOAuth2Request().getClientId();
    if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
        throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
    }
    // clear out any access tokens already associated with the refresh
    // token.
    tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
    if (isExpired(refreshToken)) {
        tokenStore.removeRefreshToken(refreshToken);
        throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
    }
    authentication = createRefreshedAuthentication(authentication, tokenRequest);
    if (!reuseRefreshToken) {
        tokenStore.removeRefreshToken(refreshToken);
        refreshToken = createRefreshToken(authentication);
    }
    OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    tokenStore.storeAccessToken(accessToken, authentication);
    if (!reuseRefreshToken) {
        tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
    }
    return accessToken;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with InvalidGrantException

use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project cuba by cuba-platform.

the class CubaUserAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String ipAddress = request.getRemoteAddr();
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug("Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");
            throw new InvalidGrantException("Authentication disabled");
        }
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String login = (String) token.getPrincipal();
        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());
            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
            // if the locale value is explicitly passed in the Accept-Language header then set its value to the
            // credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }
            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }
        AppContext.setSecurityContext(new SecurityContext(session));
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }
    return null;
}
Also used : RestApiConfig(com.haulmont.restapi.config.RestApiConfig) Locale(java.util.Locale) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) LockedException(org.springframework.security.authentication.LockedException) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) LoginPasswordCredentials(com.haulmont.cuba.security.auth.LoginPasswordCredentials) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) RestApiAccessDeniedException(com.haulmont.cuba.security.global.RestApiAccessDeniedException) Map(java.util.Map)

Aggregations

InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)14 Authentication (org.springframework.security.core.Authentication)10 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)4 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)3 InvalidRequestException (org.springframework.security.oauth2.common.exceptions.InvalidRequestException)3 Transactional (org.springframework.transaction.annotation.Transactional)3 OAuth2AccessTokenResult (com.haulmont.restapi.auth.OAuthTokenIssuer.OAuth2AccessTokenResult)2 Date (java.util.Date)2 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)2 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)2 RedirectMismatchException (org.springframework.security.oauth2.common.exceptions.RedirectMismatchException)2 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)1 LoginPasswordCredentials (com.haulmont.cuba.security.auth.LoginPasswordCredentials)1