Search in sources :

Example 91 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project summerb by skarpushin.

the class ControllerExceptionHandlerStrategyLegacyImpl method buildHtmlError.

protected ModelAndView buildHtmlError(Throwable ex) {
    if (securityContextResolver != null && (ex instanceof AccessDeniedException && !securityContextResolver.hasRole(Roles.ROLE_USER))) {
        throw new IllegalArgumentException("Exception will not be handled by default exception handler: " + ex);
    }
    log.error("Exception occured", ex);
    ModelAndView ret = new ModelAndView(Views.ERROR_UNEXPECTED_CLARIFIED);
    String msg = exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale());
    if (!StringUtils.hasText(msg)) {
        msg = ExceptionUtils.getAllMessagesRaw(ex);
    }
    ControllerBase.addPageMessage(ret.getModel(), new PageMessage(msg, MessageSeverity.Danger));
    ret.getModel().put(ControllerBase.ATTR_EXCEPTION, msg);
    ret.getModel().put(ControllerBase.ATTR_EXCEPTION_STACKTRACE, ExceptionUtils.getThrowableStackTraceAsString(ex));
    return ret;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) PageMessage(org.summerb.webappboilerplate.model.PageMessage) ModelAndView(org.springframework.web.servlet.ModelAndView)

Example 92 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project summerb by skarpushin.

the class ControllerExceptionHandlerStrategyLegacyImpl method buildJsonError.

/**
 * This peace of crap needs to be removed. Because in case of JSON it's rest
 * API, there is no place for {@link ModelAndView}. Response should be pure JSON
 * content.
 *
 * So instead of implementing it here it's better to just re-throw exception and
 * let {@link RestExceptionTranslator} handle it and gracefully convert it into
 * json description of error happened
 */
protected ModelAndView buildJsonError(Throwable ex, HttpServletRequest req, HttpServletResponse res) {
    String msg = exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale());
    NotAuthorizedException nae;
    FieldValidationException fve;
    AccessDeniedException ade;
    boolean translateAuthExc = Boolean.TRUE.equals(Boolean.valueOf(req.getHeader(RestExceptionTranslator.X_TRANSLATE_AUTHORIZATION_ERRORS)));
    if ((nae = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class)) != null) {
        NotAuthorizedResult naeResult = nae.getResult();
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(naeResult, res);
            return null;
        }
    } else if ((ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class)) != null) {
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(new NotAuthorizedResult(getCurrentUser(), SecurityMessageCodes.ACCESS_DENIED), res);
            return null;
        }
    } else if ((fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class)) != null) {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ValidationErrorsVm vepm = new ValidationErrorsVm(fve.getErrors());
        return new ModelAndView(jsonView, ControllerBase.ATTR_VALIDATION_ERRORS, vepm.getMsg());
    }
    log.warn("Failed to process request", ex);
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ValidationErrorsVm(org.summerb.webappboilerplate.model.ValidationErrorsVm) ModelAndView(org.springframework.web.servlet.ModelAndView) NotAuthorizedResult(org.summerb.security.api.dto.NotAuthorizedResult) NotAuthorizedException(org.summerb.security.api.exceptions.NotAuthorizedException)

Example 93 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project summerb by skarpushin.

the class RestExceptionTranslator method determineFailureResult.

protected DtoBase determineFailureResult(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    // first see if it is FVE
    FieldValidationException fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class);
    if (fve != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return fve.getErrorDescriptionObject();
    }
    boolean translateAuthErrors = Boolean.TRUE.equals(Boolean.valueOf(request.getHeader(X_TRANSLATE_AUTHORIZATION_ERRORS)));
    GenericServerErrorResult ret = null;
    if (translateAuthErrors) {
        ret = new GenericServerErrorResult(buildUserMessage(ex, request), new ExceptionInfo(ex));
    }
    NotAuthorizedException naex = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class);
    if (naex != null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : naex.getResult();
    }
    AuthenticationException ae = ExceptionUtils.findExceptionOfType(ex, AuthenticationException.class);
    if (ae != null) {
        // NOTE: See how we did that in AuthenticationFailureHandlerImpl...
        // Looks like we need to augment our custom RestLoginFilter so it
        // will put username to request
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult("(username not resolved)", SecurityMessageCodes.AUTH_FATAL);
    }
    AccessDeniedException ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class);
    if (ade != null) {
        if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.ACCESS_DENIED);
    }
    CurrentUserNotFoundException cunfe = ExceptionUtils.findExceptionOfType(ex, CurrentUserNotFoundException.class);
    if (cunfe != null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
    }
    // TBD: Do we really need to send whole stack trace to client ??? I think we
    // should do it only during development
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new GenericServerErrorResult(buildUserMessage(ex, request), new ExceptionInfo(ex));
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) AuthenticationException(org.springframework.security.core.AuthenticationException) NotAuthorizedResult(org.summerb.security.api.dto.NotAuthorizedResult) CurrentUserNotFoundException(org.summerb.security.api.CurrentUserNotFoundException) NotAuthorizedException(org.summerb.security.api.exceptions.NotAuthorizedException) GenericServerErrorResult(org.summerb.utils.exceptions.dto.GenericServerErrorResult) ExceptionInfo(org.summerb.utils.exceptions.dto.ExceptionInfo)

Example 94 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException 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 95 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project spring-security-oauth by spring-projects.

the class ClientScopeVoter method vote.

public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int result = ACCESS_ABSTAIN;
    if (!(authentication instanceof OAuth2Authentication)) {
        return result;
    }
    OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
    OAuth2Request clientAuthentication = oauth2Authentication.getOAuth2Request();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuthentication.getClientId());
    Set<String> scopes = clientAuthentication.getScope();
    if (oauth2Authentication.isClientOnly() && clientAuthoritiesAreScopes) {
        scopes = AuthorityUtils.authorityListToSet(clientAuthentication.getAuthorities());
    }
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            result = ACCESS_GRANTED;
            for (String scope : scopes) {
                if (!client.getScope().contains(scope)) {
                    result = ACCESS_DENIED;
                    break;
                }
            }
            if (result == ACCESS_DENIED && throwException) {
                InsufficientScopeException failure = new InsufficientScopeException("Insufficient scope for this resource", client.getScope());
                throw new AccessDeniedException(failure.getMessage(), failure);
            }
            return result;
        }
    }
    return result;
}
Also used : InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) ConfigAttribute(org.springframework.security.access.ConfigAttribute) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Aggregations

AccessDeniedException (org.springframework.security.access.AccessDeniedException)189 Test (org.junit.Test)32 Test (org.junit.jupiter.api.Test)21 Authentication (org.springframework.security.core.Authentication)18 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)17 ArrayList (java.util.ArrayList)15 ApplicationUser (org.finra.herd.model.dto.ApplicationUser)14 SecurityUserWrapper (org.finra.herd.model.dto.SecurityUserWrapper)14 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)13 Method (java.lang.reflect.Method)12 JoinPoint (org.aspectj.lang.JoinPoint)11 MethodSignature (org.aspectj.lang.reflect.MethodSignature)11 SecurityContext (org.springframework.security.core.context.SecurityContext)11 NamespaceAuthorization (org.finra.herd.model.api.xml.NamespaceAuthorization)10 Credential (com.sequenceiq.cloudbreak.domain.Credential)8 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)8 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)8 ModelAndView (org.springframework.web.servlet.ModelAndView)8 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)7