Search in sources :

Example 61 with OAuth2Exception

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

the class HttpMethodNotSupportedAdvice method handleMethodNotSupportedException.

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<OAuth2Exception> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException e) throws Exception {
    logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(e);
    if (HttpMethod.POST.matches(e.getMethod())) {
        OAuth2Exception cause = new OAuth2Exception("Parameters must be passed in the body of the request", result.getBody().getCause()) {

            public String getOAuth2ErrorCode() {
                return "query_string_not_allowed";
            }

            public int getHttpErrorCode() {
                return NOT_ACCEPTABLE.value();
            }
        };
        result = new ResponseEntity<>(cause, result.getHeaders(), NOT_ACCEPTABLE);
    }
    return result;
}
Also used : OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler)

Example 62 with OAuth2Exception

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

the class CustomWebResponseExceptionTranslator method translate.

@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) {
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception exception = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (exception != null) {
        // return handleOAuth2Exception(new CustomOAuth2Exception(e.getMessage(), e));
        OAuth2Exception ex = new CustomOAuth2Exception(e.getMessage(), e);
        int status = ex.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, ex.getSummary()));
        }
        if (e instanceof ClientAuthenticationException) {
            return new ResponseEntity<>(ex, headers, HttpStatus.valueOf(status));
        }
        Result<String> result = Result.fail(SystemResultCode.INVALID_ACCESS_TOKEN, ex.getMessage());
        return new ResponseEntity(result, headers, HttpStatus.valueOf(status));
    }
    exception = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (exception != null) {
        return handleOAuth2Exception(new CustomOAuth2Exception(exception.getMessage(), exception));
    }
    exception = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain);
    if (exception != null) {
        return handleOAuth2Exception(new CustomOAuth2Exception(exception.getMessage(), exception));
    }
    exception = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (exception != null) {
        return handleOAuth2Exception(new CustomOAuth2Exception(exception.getMessage(), exception));
    }
    exception = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (exception != null) {
        return handleOAuth2Exception((OAuth2Exception) exception);
    }
    return handleOAuth2Exception(new CustomOAuth2Exception(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException) AuthenticationException(org.springframework.security.core.AuthenticationException) CustomOAuth2Exception(me.dwliu.framework.integration.security.exception.CustomOAuth2Exception) CustomOAuth2Exception(me.dwliu.framework.integration.security.exception.CustomOAuth2Exception) ClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException) 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) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) ClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException) ResponseEntity(org.springframework.http.ResponseEntity) CustomOAuth2Exception(me.dwliu.framework.integration.security.exception.CustomOAuth2Exception) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 63 with OAuth2Exception

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

the class CustomAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) {
    String userName = authentication.getName();
    String password = authentication.getCredentials().toString();
    final LinkedHashMap<String, String> details = (LinkedHashMap<String, String>) authentication.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;
    RequestInfo requestInfo;
    try {
        user = userService.getUniqueUser(userName, tenantId, UserType.fromValue(userType));
        /* decrypt here otp service and final response need decrypted data*/
        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.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.getActive() == null || !user.getActive()) {
        throw new OAuth2Exception("Please activate your account");
    }
    if (user.getAccountLocked() != null && user.getAccountLocked()) {
        if (userService.isAccountUnlockAble(user)) {
            user = unlockAccount(user, requestInfo);
        } else
            throw new OAuth2Exception("Account locked");
    }
    boolean isCitizen = false;
    if (user.getType() != null && user.getType().equals(UserType.CITIZEN))
        isCitizen = true;
    boolean isPasswordMatched;
    if (isCitizen) {
        if (fixedOTPEnabled && !fixedOTPPassword.equals("") && fixedOTPPassword.equals(password)) {
            // for automation allow fixing otp validation to a fixed otp
            isPasswordMatched = true;
        } else {
            isPasswordMatched = isPasswordMatch(citizenLoginPasswordOtpEnabled, password, user, authentication);
        }
    } else {
        isPasswordMatched = isPasswordMatch(employeeLoginPasswordOtpEnabled, password, user, authentication);
    }
    if (isPasswordMatched) {
        /*
			  We assume that there will be only one type. If it is multiple
			  then we have change below code Separate by comma or other and
			  iterate
			 */
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_" + user.getType()));
        final SecureUser secureUser = new SecureUser(getUser(user));
        userService.resetFailedLoginAttempts(user);
        return new UsernamePasswordAuthenticationToken(secureUser, password, grantedAuths);
    } else {
        // Handle failed login attempt
        // Fetch Real IP after being forwarded by reverse proxy
        userService.handleFailedLogin(user, request.getHeader(IP_HEADER_NAME), requestInfo);
        throw new OAuth2Exception("Invalid login credentials");
    }
}
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) Role(org.egov.user.web.contract.auth.Role) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 64 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project tumo-boot by Tumo-Team.

the class TumoWebResponseExceptionTranslator method translate.

/**
 * @author tycoding
 * @see org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator
 * @since 2020/10/16
 */
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(e);
    // 请求未授权
    Exception ase = (AuthenticationException) this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
        return this.handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }
    // 拒绝访问异常
    ase = (AccessDeniedException) this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase != null) {
        return this.handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }
    // Token失效异常
    ase = (org.springframework.security.oauth2.common.exceptions.InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(org.springframework.security.oauth2.common.exceptions.InvalidGrantException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new InvalidGrantException(ase.getMessage(), ase));
    }
    // 请求方法不支持异常
    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new MethodNotAllowedException(ase.getMessage(), ase));
    }
    // OAuth2Exception异常
    ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (ase != null) {
        return this.handleOAuth2Exception((OAuth2Exception) ase);
    }
    return handleOAuth2Exception(new ServerErrorException(HttpCode.INTERNAL_SERVER_ERROR.getMsg(), e));
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) IOException(java.io.IOException) 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)

Example 65 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project faf-java-api by FAForever.

the class JsonApiOAuthMessageConverter method transformObject.

protected Object transformObject(Object object) {
    ErrorResponse response = new ErrorResponse();
    if (object instanceof OAuth2Exception) {
        OAuth2Exception oAuth2Exception = (OAuth2Exception) object;
        final ErrorResult newError = new ErrorResult(String.valueOf(oAuth2Exception.getHttpErrorCode()), oAuth2Exception.getOAuth2ErrorCode(), oAuth2Exception.getMessage());
        response.addError(newError);
        newError.setMeta(ErrorResult.createMeta(null, oAuth2Exception.getAdditionalInformation()).orElse(null));
    } else {
        response.addError(new ErrorResult(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "Error", object.toString()));
    }
    return response;
}
Also used : ErrorResult(com.faforever.api.error.ErrorResult) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ErrorResponse(com.faforever.api.error.ErrorResponse)

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