Search in sources :

Example 1 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project ballcat by ballcat-projects.

the class CustomWebResponseExceptionTranslator 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 = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain);
    if (ase != null) {
        // 这里必须配置 messageSource,且指定的 basename 包含
        // ”org.springframework.security.messages“,否则错误信息没有国际化
        // {@link https://github.com/spring-projects/spring-security/issues/10227}
        CustomInvalidGrantException customInvalidGrantException = new CustomInvalidGrantException(ase.getMessage());
        return handleOAuth2Exception(customInvalidGrantException);
    }
    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new CustomWebResponseExceptionTranslator.UnauthorizedException(e.getMessage(), e));
    }
    ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new CustomWebResponseExceptionTranslator.ForbiddenException(ase.getMessage(), ase));
    }
    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }
    // 放到最后,OAuth2 项目没有异常消息没有国际化
    ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }
    return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
}
Also used : InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

Example 2 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project uaa by cloudfoundry.

the class UaaAuthorizationEndpoint method getImplicitGrantOrHybridResponse.

// We can grant a token and return it with implicit approval.
private ModelAndView getImplicitGrantOrHybridResponse(AuthorizationRequest authorizationRequest, Authentication authentication, String grantType) {
    OAuth2AccessToken accessToken;
    try {
        TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, GRANT_TYPE_IMPLICIT);
        Map<String, String> requestParameters = new HashMap<>(authorizationRequest.getRequestParameters());
        requestParameters.put(GRANT_TYPE, grantType);
        authorizationRequest.setRequestParameters(requestParameters);
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        accessToken = getAccessTokenForImplicitGrantOrHybrid(tokenRequest, storedOAuth2Request, grantType);
        if (accessToken == null) {
            throw new UnsupportedResponseTypeException("Unsupported response type: token or id_token");
        }
        return new ModelAndView(new RedirectView(buildRedirectURI(authorizationRequest, accessToken, authentication), false, true, false));
    } catch (OAuth2Exception e) {
        return new ModelAndView(new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false));
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) HashMap(java.util.HashMap) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ImplicitTokenRequest(org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) UnsupportedResponseTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 3 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project uaa by cloudfoundry.

the class UaaAuthorizationEndpoint method generateCode.

private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) throws AuthenticationException {
    try {
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication);
        return authorizationCodeServices.createAuthorizationCode(combinedAuth);
    } catch (OAuth2Exception e) {
        if (authorizationRequest.getState() != null) {
            e.addAdditionalInformation("state", authorizationRequest.getState());
        }
        throw e;
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 4 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project core-services by digit-egov.

the class CustomAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Class<? extends Authentication> toTest = authentication.getClass();
    Authentication result = null;
    for (AuthenticationProvider provider : authenticationProviders) {
        if (!provider.supports(toTest)) {
            continue;
        }
        log.debug("Authentication attempt using " + provider.getClass().getName());
        try {
            result = provider.authenticate(authentication);
            if (result != null) {
                copyDetails(authentication, result);
                break;
            }
        } catch (AccountStatusException | InternalAuthenticationServiceException e) {
            // invalid account status
            throw e;
        } catch (AuthenticationException e) {
            log.error("Unable to authenticate", e);
        }
    }
    if (result != null) {
        if (eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
            // Authentication is complete. Remove credentials and other secret data
            // from authentication
            ((CredentialsContainer) result).eraseCredentials();
        }
        return result;
    } else
        throw new OAuth2Exception("AUTHENTICATION_FAILURE, unable to authenticate user");
}
Also used : CredentialsContainer(org.springframework.security.core.CredentialsContainer) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 5 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project core-services by digit-egov.

the class CustomPreAuthenticatedProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication.getPrincipal();
    SecureUser secureUser = (SecureUser) token.getPrincipal();
    String userName = secureUser.getUsername();
    final LinkedHashMap<String, String> details = (LinkedHashMap<String, String>) token.getDetails();
    String tenantId = details.get("tenantId");
    String userType = details.get("userType");
    if (isEmpty(tenantId)) {
        throw new OAuth2Exception("TenantId is mandatory");
    }
    if (isEmpty(userType) || isNull(UserType.fromValue(userType))) {
        throw new OAuth2Exception("User Type is mandatory and has to be a valid type");
    }
    User user;
    try {
        user = userService.getUniqueUser(userName, tenantId, UserType.fromValue(userType));
        /* decrypt here */
        Set<org.egov.user.domain.model.Role> domain_roles = user.getRoles();
        List<org.egov.common.contract.request.Role> contract_roles = new ArrayList<>();
        for (org.egov.user.domain.model.Role role : domain_roles) {
            contract_roles.add(org.egov.common.contract.request.Role.builder().code(role.getCode()).name(role.getName()).build());
        }
        org.egov.common.contract.request.User userInfo = org.egov.common.contract.request.User.builder().uuid(user.getUuid()).type(user.getType() != null ? user.getType().name() : null).roles(contract_roles).build();
        RequestInfo requestInfo = RequestInfo.builder().userInfo(userInfo).build();
        user = encryptionDecryptionUtil.decryptObject(user, "User", User.class, requestInfo);
    } catch (UserNotFoundException e) {
        log.error("User not found", e);
        throw new OAuth2Exception("Invalid login credentials");
    } catch (DuplicateUserNameException e) {
        log.error("Fatal error, user conflict, more than one user found", e);
        throw new OAuth2Exception("Invalid login credentials");
    }
    if (user.getAccountLocked() == null || user.getAccountLocked()) {
        throw new OAuth2Exception("Account locked");
    }
    List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_" + user.getType()));
    final SecureUser finalUser = new SecureUser(getUser(user));
    return new PreAuthenticatedAuthenticationToken(finalUser, null, grantedAuths);
}
Also used : UserNotFoundException(org.egov.user.domain.exception.UserNotFoundException) User(org.egov.user.domain.model.User) SecureUser(org.egov.user.domain.model.SecureUser) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) RequestInfo(org.egov.common.contract.request.RequestInfo) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DuplicateUserNameException(org.egov.user.domain.exception.DuplicateUserNameException) SecureUser(org.egov.user.domain.model.SecureUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Role(org.egov.user.web.contract.auth.Role) 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