Search in sources :

Example 46 with AccessDeniedException

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

the class GlobalMethodSecurityBeanDefinitionParserTests method supportsCustomAuthenticationManager.

@Test
public void supportsCustomAuthenticationManager() throws Exception {
    setContext("<b:bean id='target' class='" + ConcreteFoo.class.getName() + "'/>" + "<method-security-metadata-source id='mds'>" + "      <protect method='" + Foo.class.getName() + ".foo' access='ROLE_ADMIN'/>" + "</method-security-metadata-source>" + "<global-method-security pre-post-annotations='enabled' metadata-source-ref='mds' authentication-manager-ref='customAuthMgr'/>" + "<b:bean id='customAuthMgr' class='org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParserTests$CustomAuthManager'>" + "      <b:constructor-arg value='authManager'/>" + "</b:bean>" + AUTH_PROVIDER_XML);
    SecurityContextHolder.getContext().setAuthentication(bob);
    Foo foo = (Foo) appContext.getBean("target");
    try {
        foo.foo(new SecurityConfig("A"));
        fail("Bob can't invoke admin methods");
    } catch (AccessDeniedException expected) {
    }
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
    foo.foo(new SecurityConfig("A"));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) SecurityConfig(org.springframework.security.access.SecurityConfig) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Test(org.junit.Test)

Example 47 with AccessDeniedException

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

the class ConsensusBased method decide.

// ~ Methods
// ========================================================================================================
/**
	 * This concrete implementation simply polls all configured
	 * {@link AccessDecisionVoter}s and upon completion determines the consensus of
	 * granted against denied responses.
	 * <p>
	 * If there were an equal number of grant and deny votes, the decision will be based
	 * on the {@link #isAllowIfEqualGrantedDeniedDecisions()} property (defaults to true).
	 * <p>
	 * If every <code>AccessDecisionVoter</code> abstained from voting, the decision will
	 * be based on the {@link #isAllowIfAllAbstainDecisions()} property (defaults to
	 * false).
	 *
	 * @param authentication the caller invoking the method
	 * @param object the secured object
	 * @param configAttributes the configuration attributes associated with the method
	 * being invoked
	 *
	 * @throws AccessDeniedException if access is denied
	 */
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
    int grant = 0;
    int deny = 0;
    int abstain = 0;
    for (AccessDecisionVoter voter : getDecisionVoters()) {
        int result = voter.vote(authentication, object, configAttributes);
        if (logger.isDebugEnabled()) {
            logger.debug("Voter: " + voter + ", returned: " + result);
        }
        switch(result) {
            case AccessDecisionVoter.ACCESS_GRANTED:
                grant++;
                break;
            case AccessDecisionVoter.ACCESS_DENIED:
                deny++;
                break;
            default:
                abstain++;
                break;
        }
    }
    if (grant > deny) {
        return;
    }
    if (deny > grant) {
        throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
    }
    if ((grant == deny) && (grant != 0)) {
        if (this.allowIfEqualGrantedDeniedDecisions) {
            return;
        } else {
            throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
        }
    }
    // To get this far, every AccessDecisionVoter abstained
    checkAllowIfAllAbstainDecisions();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) AccessDecisionVoter(org.springframework.security.access.AccessDecisionVoter)

Example 48 with AccessDeniedException

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

the class InMemoryUserDetailsManager method changePassword.

public void changePassword(String oldPassword, String newPassword) {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
    if (currentUser == null) {
        // This would indicate bad coding somewhere
        throw new AccessDeniedException("Can't change password as no Authentication object found in context " + "for current user.");
    }
    String username = currentUser.getName();
    logger.debug("Changing password for user '" + username + "'");
    // supplied password.
    if (authenticationManager != null) {
        logger.debug("Reauthenticating user '" + username + "' for password change request.");
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
    } else {
        logger.debug("No authentication manager set. Password won't be re-checked.");
    }
    MutableUserDetails user = users.get(username);
    if (user == null) {
        throw new IllegalStateException("Current user doesn't exist in database.");
    }
    user.setPassword(newPassword);
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 49 with AccessDeniedException

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

the class JdbcUserDetailsManager method changePassword.

public void changePassword(String oldPassword, String newPassword) throws AuthenticationException {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
    if (currentUser == null) {
        // This would indicate bad coding somewhere
        throw new AccessDeniedException("Can't change password as no Authentication object found in context " + "for current user.");
    }
    String username = currentUser.getName();
    // supplied password.
    if (authenticationManager != null) {
        logger.debug("Reauthenticating user '" + username + "' for password change request.");
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
    } else {
        logger.debug("No authentication manager set. Password won't be re-checked.");
    }
    logger.debug("Changing password for user '" + username + "'");
    getJdbcTemplate().update(changePasswordSql, newPassword, username);
    SecurityContextHolder.getContext().setAuthentication(createNewAuthentication(currentUser, newPassword));
    userCache.removeUserFromCache(username);
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 50 with AccessDeniedException

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

the class MethodSecurityInterceptorTests method callIsntMadeWhenAccessDecisionManagerRejectsAccess.

@Test
public void callIsntMadeWhenAccessDecisionManagerRejectsAccess() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(token);
    // Use mocked target to make sure invocation doesn't happen (not in expectations
    // so test would fail)
    createTarget(true);
    mdsReturnsUserRole();
    when(authman.authenticate(token)).thenReturn(token);
    doThrow(new AccessDeniedException("rejected")).when(adm).decide(any(Authentication.class), any(MethodInvocation.class), any(List.class));
    try {
        advisedTarget.makeUpperCase("HELLO");
        fail("Expected Exception");
    } catch (AccessDeniedException expected) {
    }
    verify(eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) Authentication(org.springframework.security.core.Authentication) MethodInvocation(org.aopalliance.intercept.MethodInvocation) AuthorizationFailureEvent(org.springframework.security.access.event.AuthorizationFailureEvent)

Aggregations

AccessDeniedException (org.springframework.security.access.AccessDeniedException)67 Test (org.junit.Test)21 Authentication (org.springframework.security.core.Authentication)14 ConfigAttribute (org.springframework.security.access.ConfigAttribute)13 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)6 ArrayList (java.util.ArrayList)5 AuthorizationFailureEvent (org.springframework.security.access.event.AuthorizationFailureEvent)5 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)5 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)5 MethodInvocation (org.aopalliance.intercept.MethodInvocation)4 Interpretation (org.hisp.dhis.interpretation.Interpretation)4 User (org.hisp.dhis.user.User)4 SecurityConfig (org.springframework.security.access.SecurityConfig)4 IOException (java.io.IOException)3 InsufficientScopeException (org.springframework.security.oauth2.common.exceptions.InsufficientScopeException)3 FilterInvocation (org.springframework.security.web.FilterInvocation)3