Search in sources :

Example 96 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project jhipster-registry by jhipster.

the class ExceptionTranslatorTest method processAccessDeniedExceptionTest.

@Test
public void processAccessDeniedExceptionTest() throws Exception {
    // These lines will throw the wanted exception
    SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenThrow(new AccessDeniedException(null));
    SecurityContextHolder.setContext(securityContext);
    MvcResult res = mock.perform(get("/api/account")).andExpect(status().isForbidden()).andReturn();
    assertThat(res.getResolvedException()).isInstanceOf(AccessDeniedException.class);
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) SecurityContext(org.springframework.security.core.context.SecurityContext) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.jupiter.api.Test)

Example 97 with AccessDeniedException

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

the class ScopeVoter method vote.

public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int result = ACCESS_ABSTAIN;
    if (!(authentication instanceof OAuth2Authentication)) {
        return result;
    }
    for (ConfigAttribute attribute : attributes) {
        if (denyAccess.equals(attribute.getAttribute())) {
            return ACCESS_DENIED;
        }
    }
    OAuth2Request clientAuthentication = ((OAuth2Authentication) authentication).getOAuth2Request();
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            result = ACCESS_DENIED;
            Set<String> scopes = clientAuthentication.getScope();
            for (String scope : scopes) {
                if (attribute.getAttribute().toUpperCase().equals((scopePrefix + scope).toUpperCase())) {
                    return ACCESS_GRANTED;
                }
            }
            if (result == ACCESS_DENIED && throwException) {
                InsufficientScopeException failure = new InsufficientScopeException("Insufficient scope for this resource", Collections.singleton(attribute.getAttribute().substring(scopePrefix.length())));
                throw new AccessDeniedException(failure.getMessage(), failure);
            }
        }
    }
    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) ConfigAttribute(org.springframework.security.access.ConfigAttribute) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 98 with AccessDeniedException

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

the class OAuth2RestTemplateTests method testTokenIsResetIfInvalid.

@Test
public void testTokenIsResetIfInvalid() throws Exception {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("TEST");
    token.setExpiration(new Date(System.currentTimeMillis() - 1000));
    restTemplate.getOAuth2ClientContext().setAccessToken(token);
    restTemplate.setAccessTokenProvider(new StubAccessTokenProvider() {

        @Override
        public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest parameters) throws UserRedirectRequiredException, AccessDeniedException {
            throw new UserRedirectRequiredException("https://www.foo.com/", Collections.<String, String>emptyMap());
        }
    });
    try {
        OAuth2AccessToken newToken = restTemplate.getAccessToken();
        assertNotNull(newToken);
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
    // planned
    }
    // context token should be reset as it clearly is invalid at this point
    assertNull(restTemplate.getOAuth2ClientContext().getAccessToken());
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) BaseOAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) Test(org.junit.Test)

Example 99 with AccessDeniedException

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

the class OAuth2AccessDeniedHandlerTests method testHandleWithJson.

@Test
public void testHandleWithJson() throws Exception {
    request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
    handler.handle(request, response, new AccessDeniedException("Bad"));
    assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
    assertTrue(response.getContentType().contains(MediaType.APPLICATION_JSON_VALUE));
    assertEquals(null, response.getErrorMessage());
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) Test(org.junit.Test)

Example 100 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project head by mifos.

the class EditStatusAction method update.

@TransactionDemarcate(validateAndResetToken = true)
@CloseSession
public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception {
    UserContext userContext = getUserContext(request);
    EditStatusActionForm editStatusActionForm = (EditStatusActionForm) form;
    Integer accountId = Integer.valueOf(editStatusActionForm.getAccountId());
    AccountBO accountBO = new AccountBusinessService().getAccount(accountId);
    Short flagId = null;
    Short newStatusId = null;
    String updateComment = editStatusActionForm.getNotes();
    if (StringUtils.isNotBlank(editStatusActionForm.getFlagId())) {
        flagId = getShortValue(editStatusActionForm.getFlagId());
    }
    if (StringUtils.isNotBlank(editStatusActionForm.getNewStatusId())) {
        newStatusId = getShortValue(editStatusActionForm.getNewStatusId());
    }
    Date trxnDate = editStatusActionForm.getTransactionDateValue(userContext.getPreferredLocale());
    if (editStatusActionForm.getNewStatusId().equals(AccountState.LOAN_APPROVED) && !AccountingRules.isBackDatedApprovalAllowed()) {
        trxnDate = new DateTimeService().getCurrentJavaDateTime();
    }
    checkPermission(accountBO, getUserContext(request), newStatusId, flagId);
    if (accountBO.isLoanAccount() || accountBO.isGroupLoanAccount()) {
        initializeLoanQuestionnaire(accountBO.getGlobalAccountNum(), newStatusId != null ? newStatusId.toString() : null);
        loanQuestionnaire.saveResponses(request, editStatusActionForm, accountId);
        //GLIM
        List<LoanBO> individualLoans = this.loanDao.findIndividualLoans(accountId);
        List<AccountUpdateStatus> updateStatus = new ArrayList<AccountUpdateStatus>(individualLoans.size() + 1);
        updateStatus.add(new AccountUpdateStatus(accountId.longValue(), newStatusId, flagId, updateComment));
        for (LoanBO individual : individualLoans) {
            updateStatus.add(new AccountUpdateStatus(individual.getAccountId().longValue(), newStatusId, flagId, updateComment));
        }
        try {
            if (individualLoans.size() == 0) {
                this.loanAccountServiceFacade.updateSingleLoanAccountStatus(updateStatus.get(0), trxnDate);
            } else {
                this.loanAccountServiceFacade.updateSeveralLoanAccountStatuses(updateStatus, trxnDate);
            }
        } catch (AccessDeniedException e) {
            throw new ServiceException(SecurityConstants.KEY_ACTIVITY_APPROVE_LOAN_NOT_ALLOWED);
        }
        return mapping.findForward(ActionForwards.loan_detail_page.toString());
    }
    if (accountBO.isSavingsAccount()) {
        AccountUpdateStatus updateStatus = new AccountUpdateStatus(accountId.longValue(), newStatusId, flagId, updateComment);
        this.savingsServiceFacade.updateSavingsAccountStatus(updateStatus);
        return mapping.findForward(ActionForwards.savings_details_page.toString());
    }
    // nothing but loan of savings account should be detected. customer account status change goes through separate action.
    return null;
}
Also used : AccountUpdateStatus(org.mifos.dto.domain.AccountUpdateStatus) EditStatusActionForm(org.mifos.accounts.struts.actionforms.EditStatusActionForm) AccessDeniedException(org.springframework.security.access.AccessDeniedException) UserContext(org.mifos.security.util.UserContext) LoanBO(org.mifos.accounts.loan.business.LoanBO) ArrayList(java.util.ArrayList) Date(java.util.Date) AccountBO(org.mifos.accounts.business.AccountBO) AccountBusinessService(org.mifos.accounts.business.service.AccountBusinessService) ServiceException(org.mifos.framework.exceptions.ServiceException) DateTimeService(org.mifos.framework.util.DateTimeService) CloseSession(org.mifos.framework.util.helpers.CloseSession) TransactionDemarcate(org.mifos.framework.util.helpers.TransactionDemarcate)

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