Search in sources :

Example 11 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project MaxKey by dromara.

the class AuthorizationEndpoint method getAuthorizationCodeResponse.

// Authorization Code Response
private View getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) {
    try {
        String successfulRedirect = getSuccessfulRedirect(authorizationRequest, generateCode(authorizationRequest, authUser));
        _logger.debug("successfulRedirect " + successfulRedirect);
        return new RedirectView(successfulRedirect, false, true, false);
    } catch (OAuth2Exception e) {
        return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, false), false, true, false);
    }
}
Also used : RedirectView(org.springframework.web.servlet.view.RedirectView) OAuth2Exception(org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception)

Example 12 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project MaxKey by dromara.

the class TokenEndpoint method postAccessToken.

@Operation(summary = "OAuth 2.0 获取AccessToken接口", description = "传递参数token等", method = "POST")
@RequestMapping(value = { OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN, OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN }, method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(@RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    // TokenEndpointAuthenticationFilter
    OAuth2AccessToken token = null;
    try {
        Object principal = WebContext.getAuthentication();
        if (!(principal instanceof Authentication)) {
            throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication.");
        }
        String clientId = getClientId((Authentication) principal);
        ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId, true);
        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(OAuth2Constants.PARAMETER.GRANT_TYPE_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());
            }
        }
        logger.debug("request parameters " + parameters);
        /**
         *crystal.sea
         * code must uuid format
         */
        if (parameters.get(OAuth2Constants.PARAMETER.CODE) != null && !StringGenerator.uuidMatches(parameters.get(OAuth2Constants.PARAMETER.CODE))) {
            throw new InvalidRequestException("The code is not valid format .");
        }
        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(OAuth2Constants.PARAMETER.SCOPE)));
        }
        // granter grant access token
        token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
        if (token == null) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }
    } catch (OAuth2Exception oauth2Exception) {
        token = new DefaultOAuth2AccessToken(oauth2Exception);
    } catch (InsufficientAuthenticationException authenticationException) {
        token = new DefaultOAuth2AccessToken(new OAuth2Exception(authenticationException.getMessage()));
    }
    return getResponse(token);
}
Also used : InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidGrantException(org.maxkey.authz.oauth2.common.exceptions.InvalidGrantException) DefaultOAuth2AccessToken(org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken) ClientDetails(org.maxkey.entity.apps.oauth2.provider.ClientDetails) OAuth2AccessToken(org.maxkey.authz.oauth2.common.OAuth2AccessToken) DefaultOAuth2AccessToken(org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken) OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) TokenRequest(org.maxkey.authz.oauth2.provider.TokenRequest) InvalidClientException(org.maxkey.authz.oauth2.common.exceptions.InvalidClientException) InvalidRequestException(org.maxkey.authz.oauth2.common.exceptions.InvalidRequestException) OAuth2Exception(org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception) UnsupportedGrantTypeException(org.maxkey.authz.oauth2.common.exceptions.UnsupportedGrantTypeException) Operation(io.swagger.v3.oas.annotations.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class WhitelabelErrorEndpoint method handleError.

@RequestMapping("/oauth/error")
public ModelAndView handleError(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    Object error = request.getAttribute("error");
    // The error summary may contain malicious user input,
    // it needs to be escaped to prevent XSS
    String errorSummary;
    if (error instanceof OAuth2Exception) {
        OAuth2Exception oauthError = (OAuth2Exception) error;
        errorSummary = HtmlUtils.htmlEscape(oauthError.getSummary());
    } else {
        errorSummary = "Unknown error";
    }
    final String errorContent = ERROR.replace("%errorSummary%", errorSummary);
    View errorView = new View() {

        @Override
        public String getContentType() {
            return "text/html";
        }

        @Override
        public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
            response.setContentType(getContentType());
            response.getWriter().append(errorContent);
        }
    };
    return new ModelAndView(errorView, model);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 14 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class DefaultWebResponseExceptionTranslator method translate.

@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    // Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }
    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }
    ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }
    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }
    return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) IOException(java.io.IOException) AuthenticationException(org.springframework.security.core.AuthenticationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 15 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class AuthorizationEndpoint method getAuthorizationCodeResponse.

private View getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) {
    try {
        RedirectView redirectView = new RedirectView(getSuccessfulRedirect(authorizationRequest, generateCode(authorizationRequest, authUser)), false, true, false);
        redirectView.setStatusCode(HttpStatus.SEE_OTHER);
        return redirectView;
    } catch (OAuth2Exception e) {
        RedirectView redirectView = new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, false), false, true, false);
        redirectView.setStatusCode(HttpStatus.SEE_OTHER);
        return redirectView;
    }
}
Also used : RedirectView(org.springframework.web.servlet.view.RedirectView) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Aggregations

OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)57 Test (org.junit.Test)15 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)13 AuthenticationException (org.springframework.security.core.AuthenticationException)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)11 Authentication (org.springframework.security.core.Authentication)9 HashMap (java.util.HashMap)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 OAuth2Exception (org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception)7 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)7 ModelAndView (org.springframework.web.servlet.ModelAndView)7 RedirectView (org.springframework.web.servlet.view.RedirectView)7 AccessDeniedException (org.springframework.security.access.AccessDeniedException)6 InsufficientScopeException (org.springframework.security.oauth2.common.exceptions.InsufficientScopeException)6 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 Date (java.util.Date)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ResponseEntity (org.springframework.http.ResponseEntity)5 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)5