Search in sources :

Example 51 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project uaa by cloudfoundry.

the class TokenMvcMockTests method test_OAuth_Authorize_API_Endpoint.

@Test
void test_OAuth_Authorize_API_Endpoint() throws Exception {
    String subdomain = "testzone" + generator.generate().toLowerCase();
    IdentityZone testZone = setupIdentityZone(subdomain, new ArrayList<>(defaultAuthorities));
    IdentityZoneHolder.set(testZone);
    setupIdentityProvider();
    String clientId = "testclient" + generator.generate();
    String scopes = "openid,uaa.user,scim.me";
    setUpClients(clientId, "", scopes, "authorization_code,password,refresh_token", true);
    String username = "testuser" + generator.generate();
    String userScopes = "";
    setUpUser(jdbcScimUserProvisioning, jdbcScimGroupMembershipManager, jdbcScimGroupProvisioning, username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());
    String uaaUserAccessToken = getUserOAuthAccessToken(mockMvc, clientId, SECRET, username, SECRET, "", testZone);
    String state = generator.generate();
    MockHttpServletRequestBuilder oauthAuthorizeGet = get("/oauth/authorize").header("Authorization", "Bearer " + uaaUserAccessToken).header("Host", subdomain + ".localhost").param(OAuth2Utils.RESPONSE_TYPE, "code").param(SCOPE, "").param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId);
    MvcResult result = mockMvc.perform(oauthAuthorizeGet).andExpect(status().is3xxRedirection()).andReturn();
    String location = result.getResponse().getHeader("Location");
    assertNotNull("Location must be present", location);
    assertThat("Location must have a code parameter.", location, containsString("code="));
    URL url = new URL(location);
    Map query = splitQuery(url);
    assertNotNull(query.get("code"));
    String code = ((List<String>) query.get("code")).get(0);
    assertNotNull(code);
    String body = mockMvc.perform(post("/oauth/token").with(httpBasic(clientId, SECRET)).header("Host", subdomain + ".localhost").accept(APPLICATION_JSON).param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE).param(OAuth2Utils.CLIENT_ID, clientId).param("code", code)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    // zone context needs to be set again because MVC calls mutate it
    IdentityZoneHolder.set(testZone);
    assertNotNull("Token body must not be null.", body);
    assertThat(body, stringContainsInOrder(Arrays.asList(ACCESS_TOKEN, REFRESH_TOKEN)));
    Map<String, Object> map = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String accessToken = (String) map.get("access_token");
    OAuth2Authentication token = tokenServices.loadAuthentication(accessToken);
    assertTrue("Must have uaa.user scope", token.getOAuth2Request().getScope().contains("uaa.user"));
}
Also used : IdentityZone(org.cloudfoundry.identity.uaa.zone.IdentityZone) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Matchers.containsString(org.hamcrest.Matchers.containsString) MvcResult(org.springframework.test.web.servlet.MvcResult) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) LinkedHashMap(java.util.LinkedHashMap) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) URL(java.net.URL) Test(org.junit.jupiter.api.Test)

Example 52 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project uaa by cloudfoundry.

the class TokenMvcMockTests method validatePasswordGrantToken.

private String validatePasswordGrantToken(String clientId, String username, String zoneSubdomain, String requestedScopes, List<String> expectedScopes) throws Exception {
    String pwdToken;
    if (zoneSubdomain == null) {
        pwdToken = testClient.getUserOAuthAccessToken(clientId, SECRET, username, SECRET, requestedScopes);
    } else {
        pwdToken = testClient.getUserOAuthAccessTokenForZone(clientId, SECRET, username, SECRET, requestedScopes, zoneSubdomain);
        IdentityZoneHolder.set(identityZoneProvisioning.retrieveBySubdomain(zoneSubdomain));
    }
    OAuth2Authentication authContext = tokenServices.loadAuthentication(pwdToken);
    Set<String> grantedScopes = authContext.getOAuth2Request().getScope();
    assertEquals(expectedScopes.size(), grantedScopes.size());
    assertEquals(grantedScopes, new HashSet<>(expectedScopes));
    IdentityZoneHolder.clear();
    return pwdToken;
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 53 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project uaa by cloudfoundry.

the class UaaAuthorizationEndpoint method generateCode.

private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) throws AuthenticationException {
    try {
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication);
        return authorizationCodeServices.createAuthorizationCode(combinedAuth);
    } catch (OAuth2Exception e) {
        if (authorizationRequest.getState() != null) {
            e.addAdditionalInformation("state", authorizationRequest.getState());
        }
        throw e;
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 54 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project uaa by cloudfoundry.

the class UaaTokenStore method deserializeOauth2Authentication.

protected OAuth2Authentication deserializeOauth2Authentication(byte[] data) {
    Map<String, Object> map = JsonUtils.readValue(data, new TypeReference<Map<String, Object>>() {
    });
    Authentication userAuthentication = null;
    if (map.get(USER_AUTHENTICATION_UAA_AUTHENTICATION) != null) {
        userAuthentication = JsonUtils.readValue((String) map.get(USER_AUTHENTICATION_UAA_AUTHENTICATION), UaaAuthentication.class);
    } else if (map.get(USER_AUTHENTICATION_UAA_PRINCIPAL) != null) {
        UaaPrincipal principal = JsonUtils.readValue((String) map.get(USER_AUTHENTICATION_UAA_PRINCIPAL), UaaPrincipal.class);
        Collection<? extends GrantedAuthority> authorities = UaaStringUtils.getAuthoritiesFromStrings((Collection<String>) map.get(USER_AUTHENTICATION_AUTHORITIES));
        userAuthentication = new UaaAuthentication(principal, (List<? extends GrantedAuthority>) authorities, UaaAuthenticationDetails.UNKNOWN);
    }
    Map<String, String> requestParameters = (Map<String, String>) map.get(OAUTH2_REQUEST_PARAMETERS);
    String clientId = (String) map.get(OAUTH2_REQUEST_CLIENT_ID);
    Collection<? extends GrantedAuthority> authorities = UaaStringUtils.getAuthoritiesFromStrings((Collection<String>) map.get(OAUTH2_REQUEST_AUTHORITIES));
    boolean approved = (boolean) map.get(OAUTH2_REQUEST_APPROVED);
    Collection<String> scope = (Collection<String>) map.get(OAUTH2_REQUEST_SCOPE);
    Collection<String> resourceIds = (Collection<String>) map.get(OAUTH2_REQUEST_RESOURCE_IDS);
    String redirectUri = (String) map.get(OAUTH2_REQUEST_REDIRECT_URI);
    Collection<String> responseTypes = (Collection<String>) map.get(OAUTH2_REQUEST_RESPONSE_TYPES);
    OAuth2Request request = new OAuth2Request(requestParameters, clientId, authorities, approved, new HashSet<>(scope), new HashSet<>(resourceIds), redirectUri, new HashSet<>(responseTypes), new HashMap<String, Serializable>());
    return new OAuth2Authentication(request, userAuthentication);
}
Also used : Serializable(java.io.Serializable) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) UaaPrincipal(org.cloudfoundry.identity.uaa.authentication.UaaPrincipal) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 55 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project uaa by cloudfoundry.

the class RemoteTokenServices method loadAuthentication.

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);
    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }
    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");
    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);
    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }
    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR, JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));
    Authentication userAuthentication = getUserAuthentication(map, scope);
    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) JsonUtils(org.cloudfoundry.identity.uaa.util.JsonUtils) HashSet(java.util.HashSet) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)538 Authentication (org.springframework.security.core.Authentication)211 Test (org.junit.Test)192 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)177 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)159 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)107 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)91 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)68 HashMap (java.util.HashMap)67 Date (java.util.Date)47 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)42 GrantedAuthority (org.springframework.security.core.GrantedAuthority)35 Map (java.util.Map)32 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)30 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)30 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)29 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)28 OAuth2Authentication (org.maxkey.authz.oauth2.provider.OAuth2Authentication)27 UaaAuthentication (org.cloudfoundry.identity.uaa.authentication.UaaAuthentication)26 HashSet (java.util.HashSet)23