Search in sources :

Example 26 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project spring-security by spring-projects.

the class AbstractAuthenticationTokenTests method testAuthoritiesAreImmutable.

@Test(expected = UnsupportedOperationException.class)
public void testAuthoritiesAreImmutable() {
    MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
    List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
    assertThat(gotAuthorities).isNotSameAs(authorities);
    gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 27 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project spring-security by spring-projects.

the class PreAuthenticatedAuthenticationTokenDeserializer method deserialize.

/**
	 * This method construct {@link PreAuthenticatedAuthenticationToken} object from serialized json.
	 * @param jp the JsonParser
	 * @param ctxt the DeserializationContext
	 * @return the user
	 * @throws IOException if a exception during IO occurs
	 * @throws JsonProcessingException if an error during JSON processing occurs
	 */
@Override
public PreAuthenticatedAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    PreAuthenticatedAuthenticationToken token = null;
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode jsonNode = mapper.readTree(jp);
    Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
    JsonNode principalNode = readJsonNode(jsonNode, "principal");
    Object principal = null;
    if (principalNode.isObject()) {
        principal = mapper.readValue(principalNode.toString(), new TypeReference<User>() {
        });
    } else {
        principal = principalNode.asText();
    }
    Object credentials = readJsonNode(jsonNode, "credentials").asText();
    List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").toString(), new TypeReference<List<GrantedAuthority>>() {
    });
    if (authenticated) {
        token = new PreAuthenticatedAuthenticationToken(principal, credentials, authorities);
    } else {
        token = new PreAuthenticatedAuthenticationToken(principal, credentials);
    }
    token.setDetails(readJsonNode(jsonNode, "details"));
    return token;
}
Also used : GrantedAuthority(org.springframework.security.core.GrantedAuthority) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) JsonNode(com.fasterxml.jackson.databind.JsonNode) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 28 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project spring-security by spring-projects.

the class SwitchUserFilter method getSourceAuthentication.

/**
	 * Find the original <code>Authentication</code> object from the current user's
	 * granted authorities. A successfully switched user should have a
	 * <code>SwitchUserGrantedAuthority</code> that contains the original source user
	 * <code>Authentication</code> object.
	 *
	 * @param current The current <code>Authentication</code> object
	 *
	 * @return The source user <code>Authentication</code> object or <code>null</code>
	 * otherwise.
	 */
private Authentication getSourceAuthentication(Authentication current) {
    Authentication original = null;
    // iterate over granted authorities and find the 'switch user' authority
    Collection<? extends GrantedAuthority> authorities = current.getAuthorities();
    for (GrantedAuthority auth : authorities) {
        // check for switch user type of authority
        if (auth instanceof SwitchUserGrantedAuthority) {
            original = ((SwitchUserGrantedAuthority) auth).getSource();
            this.logger.debug("Found original switch user granted authority [" + original + "]");
        }
    }
    return original;
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 29 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project spring-security-oauth by spring-projects.

the class OAuthProcessingFilterTests method testValidateSignature.

/**
	 * test validating the signature.
	 */
@Test
public void testValidateSignature() throws Exception {
    OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {

        @Override
        protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        }
    };
    ConsumerDetails details = mock(ConsumerDetails.class);
    SignatureSecret secret = mock(SignatureSecret.class);
    OAuthProviderToken token = mock(OAuthProviderToken.class);
    OAuthSignatureMethod sigMethod = mock(OAuthSignatureMethod.class);
    ConsumerCredentials credentials = new ConsumerCredentials("id", "sig", "method", "base", "token");
    when(details.getAuthorities()).thenReturn(new ArrayList<GrantedAuthority>());
    when(details.getSignatureSecret()).thenReturn(secret);
    filter.setTokenServices(tokenServices);
    when(tokenServices.getToken("token")).thenReturn(token);
    filter.setSignatureMethodFactory(signatureFactory);
    when(token.getSecret()).thenReturn("shhh!!!");
    when(signatureFactory.getSignatureMethod("method", secret, "shhh!!!")).thenReturn(sigMethod);
    ConsumerAuthentication authentication = new ConsumerAuthentication(details, credentials);
    filter.validateSignature(authentication);
    verify(sigMethod).verify("base", "sig");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SignatureSecret(org.springframework.security.oauth.common.signature.SignatureSecret) OAuthProviderToken(org.springframework.security.oauth.provider.token.OAuthProviderToken) ConsumerCredentials(org.springframework.security.oauth.provider.ConsumerCredentials) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthSignatureMethod(org.springframework.security.oauth.common.signature.OAuthSignatureMethod) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails) Test(org.junit.Test)

Example 30 with GrantedAuthority

use of org.springframework.security.core.GrantedAuthority in project spring-security-oauth by spring-projects.

the class OAuthProcessingFilterTests method testDoFilter.

/**
	 * tests do filter.
	 */
@Test
public void testDoFilter() throws Exception {
    final boolean[] triggers = new boolean[2];
    Arrays.fill(triggers, false);
    OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {

        @Override
        protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
            return true;
        }

        protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(null, null);
        }

        @Override
        protected void validateOAuthParams(ConsumerDetails consumerDetails, Map<String, String> oauthParams) throws InvalidOAuthParametersException {
            triggers[0] = true;
        }

        @Override
        protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
            triggers[1] = true;
        }

        @Override
        protected void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failure) throws IOException, ServletException {
            throw failure;
        }

        @Override
        protected Object createDetails(HttpServletRequest request, ConsumerDetails consumerDetails) {
            return null;
        }

        @Override
        protected void resetPreviousAuthentication(Authentication previousAuthentication) {
        // no-op
        }

        @Override
        protected boolean skipProcessing(HttpServletRequest request) {
            return false;
        }
    };
    filter.setProviderSupport(providerSupport);
    filter.setConsumerDetailsService(consumerDetailsService);
    filter.setNonceServices(nonceServices);
    filter.setSignatureMethodFactory(signatureFactory);
    filter.setTokenServices(tokenServices);
    when(request.getMethod()).thenReturn("DELETE");
    filter.doFilter(request, response, filterChain);
    verify(response).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    assertFalse(triggers[0]);
    assertFalse(triggers[1]);
    Arrays.fill(triggers, false);
    when(request.getMethod()).thenReturn("GET");
    HashMap<String, String> requestParams = new HashMap<String, String>();
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    try {
        filter.doFilter(request, response, filterChain);
        fail("should have required a consumer key.");
    } catch (InvalidOAuthParametersException e) {
        assertFalse(triggers[0]);
        assertFalse(triggers[1]);
        Arrays.fill(triggers, false);
    }
    when(request.getMethod()).thenReturn("GET");
    requestParams = new HashMap<String, String>();
    requestParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(), "consumerKey");
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    ConsumerDetails consumerDetails = mock(ConsumerDetails.class);
    when(consumerDetails.getAuthorities()).thenReturn(new ArrayList<GrantedAuthority>());
    when(consumerDetailsService.loadConsumerByConsumerKey("consumerKey")).thenReturn(consumerDetails);
    requestParams.put(OAuthConsumerParameter.oauth_token.toString(), "tokenvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature_method.toString(), "methodvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature.toString(), "signaturevalue");
    when(providerSupport.getSignatureBaseString(request)).thenReturn("sigbasestring");
    filter.doFilter(request, response, filterChain);
    verify(filterChain).doFilter(null, null);
    verify(request).setAttribute(OAuthProviderProcessingFilter.OAUTH_PROCESSING_HANDLED, Boolean.TRUE);
    ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication();
    assertSame(consumerDetails, authentication.getConsumerDetails());
    assertEquals("tokenvalue", authentication.getConsumerCredentials().getToken());
    assertEquals("methodvalue", authentication.getConsumerCredentials().getSignatureMethod());
    assertEquals("signaturevalue", authentication.getConsumerCredentials().getSignature());
    assertEquals("sigbasestring", authentication.getConsumerCredentials().getSignatureBaseString());
    assertEquals("consumerKey", authentication.getConsumerCredentials().getConsumerKey());
    assertTrue(authentication.isSignatureValidated());
    SecurityContextHolder.getContext().setAuthentication(null);
    assertTrue(triggers[0]);
    assertTrue(triggers[1]);
    Arrays.fill(triggers, false);
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) HashMap(java.util.HashMap) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HashMap(java.util.HashMap) Map(java.util.Map) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails) Test(org.junit.Test)

Aggregations

GrantedAuthority (org.springframework.security.core.GrantedAuthority)158 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)79 Authentication (org.springframework.security.core.Authentication)51 Test (org.junit.Test)35 ArrayList (java.util.ArrayList)33 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)33 HashSet (java.util.HashSet)22 UserDetails (org.springframework.security.core.userdetails.UserDetails)16 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)15 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)11 SecurityContext (org.springframework.security.core.context.SecurityContext)11 User (org.springframework.security.core.userdetails.User)10 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)10 MifosUser (org.mifos.security.MifosUser)9 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 DistinguishedName (org.springframework.ldap.core.DistinguishedName)7 AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)7 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)7