Search in sources :

Example 11 with InvalidGrantException

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

the class IdpAuthController method postAccessToken.

@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters, HttpServletRequest request) throws HttpRequestMethodNotSupportedException {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");
        throw new InvalidGrantException("IDP is not supported");
    }
    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
    }
    // we cannot perform brute-force check here, since we don't know username
    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();
    OAuth2AccessTokenResult tokenResult = authenticate(idpTicket, request.getLocale(), ipAddress, parameters);
    return ResponseEntity.ok(tokenResult.getAccessToken());
}
Also used : OAuth2AccessTokenResult(com.haulmont.restapi.auth.OAuthTokenIssuer.OAuth2AccessTokenResult) Authentication(org.springframework.security.core.Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

Example 12 with InvalidGrantException

use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException 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={}, clientId={}, scope={}", new Object[] { authorizationCode, 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) {
        if (Features.REVOKE_TOKEN_ON_CODE_REUSE.isActive()) {
            int numDisabled = orcidOauthTokenDetailService.disableAccessTokenByCodeAndClient(authorizationCode, tokenRequest.getClientId(), RevokeReason.AUTH_CODE_REUSED);
            if (numDisabled > 0) {
                throw new InvalidGrantException("Reused authorization code: " + authorizationCode);
            }
        }
        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;
    try {
        storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    } catch (InvalidGrantException e) {
        throw e;
    }
    OAuth2Request pendingAuthorizationRequest = storedAuth.getOAuth2Request();
    // Regenerate the authorization request but now with the request parameters
    pendingAuthorizationRequest = pendingAuthorizationRequest.createOAuth2Request(parameters);
    LOGGER.debug("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();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        LOGGER.error("Exception exchanging authentication code {}, client ID mismatch: pendingClientId={}, authorizationRequest.clientId={}", new Object[] { authorizationCode, pendingClientId, clientId });
        // 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 13 with InvalidGrantException

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

the class OrcidClientCredentialEndPointDelegatorImpl method obtainOauth2Token.

@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
    String code = formParams.getFirst("code");
    String clientId = formParams.getFirst(OrcidOauth2Constants.CLIENT_ID_PARAM);
    String state = formParams.getFirst(OrcidOauth2Constants.STATE_PARAM);
    String redirectUri = formParams.getFirst(OrcidOauth2Constants.REDIRECT_URI_PARAM);
    String refreshToken = formParams.getFirst(OrcidOauth2Constants.REFRESH_TOKEN);
    String scopeList = formParams.getFirst(OrcidOauth2Constants.SCOPE_PARAM);
    String grantType = formParams.getFirst(OrcidOauth2Constants.GRANT_TYPE);
    Boolean revokeOld = formParams.containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(formParams.getFirst(OrcidOauth2Constants.REVOKE_OLD)) : true;
    Long expiresIn = calculateExpiresIn(formParams);
    String bearerToken = null;
    Set<String> scopes = new HashSet<String>();
    if (StringUtils.isNotEmpty(scopeList)) {
        scopes = OAuth2Utils.parseParameterList(scopeList);
    }
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        if (!PojoUtil.isEmpty(authorization)) {
            if ((authorization.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = authorization.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                bearerToken = authHeaderValue;
                if (PojoUtil.isEmpty(bearerToken)) {
                    throw new IllegalArgumentException("Refresh token request doesnt include the authorization");
                }
            }
        }
    }
    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.error("Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }
    /**
     * Patch, update any orcid-grants scope to funding scope
     */
    for (String scope : scopes) {
        if (scope.contains("orcid-grants")) {
            String newScope = scope.replace("orcid-grants", "funding");
            LOGGER.info("Client {} provided a grants scope {} which will be updated to {}", new Object[] { clientId, scope, newScope });
            scopes.remove(scope);
            scopes.add(newScope);
        }
    }
    try {
        if (scopes != null) {
            List<String> toRemove = new ArrayList<String>();
            for (String scope : scopes) {
                ScopePathType scopeType = ScopePathType.fromValue(scope);
                if (scopeType.isInternalScope()) {
                    // You should not allow any internal scope here! go away!
                    String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
                    throw new OrcidInvalidScopeException(message);
                } else if (OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
                    if (!scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                } else {
                    if (scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                }
            }
            for (String remove : toRemove) {
                scopes.remove(remove);
            }
        }
    } catch (IllegalArgumentException iae) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }
    try {
        OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state, bearerToken, revokeOld, expiresIn);
        return getResponse(token);
    } catch (InvalidGrantException e) {
        // this needs to be caught here so the transaction doesn't roll back
        OAuthError error = OAuthErrorUtils.getOAuthError(e);
        Status status = Status.fromStatusCode(error.getResponseStatus().getStatusCode());
        return Response.status(status).entity(error).build();
    }
}
Also used : Status(com.sun.jersey.api.client.ClientResponse.Status) OrcidInvalidScopeException(org.orcid.core.exception.OrcidInvalidScopeException) ArrayList(java.util.ArrayList) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) AbstractEndpoint(org.springframework.security.oauth2.provider.endpoint.AbstractEndpoint) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) OAuthError(org.orcid.core.oauth.OAuthError) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 14 with InvalidGrantException

use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project spring-cloud-framework by zhuwj921.

the class LoginController method login.

@ApiOperation(value = "pc端登入接口", notes = "pc端登入接口")
@PostMapping("/login")
public Result<OAuth2AccessToken> login(@RequestParam Map<String, String> parameters) {
    try {
        logger.info("login  start ......");
        // 设置授权类型为密码模式
        parameters.put("grant_type", "password");
        Collection<GrantedAuthority> grantedAuthorities = new HashSet<>();
        // 此处不能为空
        grantedAuthorities.add(new SimpleGrantedAuthority("admin"));
        Authentication authentication = new UsernamePasswordAuthenticationToken("webapp", "webapp", grantedAuthorities);
        ResponseEntity<OAuth2AccessToken> responseEntity = tokenEndpoint.postAccessToken(authentication, parameters);
        logger.info("login  end ......");
        return Result.ok(responseEntity.getBody());
    } catch (InvalidGrantException e) {
        logger.error("login error  用户名密码不正确 ....", e);
        return Result.error("用户名密码不正确");
    } catch (Exception e) {
        logger.error("login error ....", e);
        return Result.error(e.getMessage());
    }
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiOperation(io.swagger.annotations.ApiOperation)

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