Search in sources :

Example 1 with InvalidRequestException

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

the class OrcidOauth2TokenEndPointFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (request.getMethod().equals(RequestMethod.GET.name())) {
        InvalidRequestException ire = new InvalidRequestException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"));
        throw new MethodNotAllowedException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"), ire);
    }
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");
    // If the request is already authenticated we can assume that this
    // filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }
    if (clientId == null) {
        throw new BadCredentialsException(localeManager.resolveMessage("apiError.client_credentials.exception"));
    }
    if (clientSecret == null) {
        clientSecret = "";
    }
    clientId = clientId.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    authentication = this.getAuthenticationManager().authenticate(authRequest);
    if (authentication != null) {
        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (PUBLIC_ROLE.equals(auth.getAuthority())) {
                InvalidRequestException ire = new InvalidRequestException(localeManager.resolveMessage("apiError.memberapi_access.exception"));
                throw new MethodNotAllowedException(localeManager.resolveMessage("apiError.memberapi_access.exception"), ire);
            }
        }
    }
    return authentication;
}
Also used : MethodNotAllowedException(org.orcid.core.security.MethodNotAllowedException) Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 2 with InvalidRequestException

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

the class OrcidWebOauth2TokenEndPointFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (request.getMethod().equals(RequestMethod.GET.name())) {
        InvalidRequestException ire = new InvalidRequestException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"));
        throw new MethodNotAllowedException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"), ire);
    }
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");
    // If the request is already authenticated we can assume that this
    // filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }
    if (clientId == null) {
        throw new BadCredentialsException(localeManager.resolveMessage("apiError.client_credentials.exception"));
    }
    if (clientSecret == null) {
        clientSecret = "";
    }
    clientId = clientId.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    return this.getAuthenticationManager().authenticate(authRequest);
}
Also used : MethodNotAllowedException(org.orcid.core.security.MethodNotAllowedException) Authentication(org.springframework.security.core.Authentication) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 3 with InvalidRequestException

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

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

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

InvalidRequestException (org.springframework.security.oauth2.common.exceptions.InvalidRequestException)15 Authentication (org.springframework.security.core.Authentication)6 Test (org.junit.Test)5 Registration (org.orcid.pojo.ajaxForm.Registration)5 DBUnitTest (org.orcid.test.DBUnitTest)5 Text (org.orcid.pojo.ajaxForm.Text)4 ArrayList (java.util.ArrayList)3 MethodNotAllowedException (org.orcid.core.security.MethodNotAllowedException)3 OrcidProfile (org.orcid.jaxb.model.message.OrcidProfile)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)3 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)3 HashMap (java.util.HashMap)2 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)2 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1