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"));
}
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;
}
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;
}
}
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);
}
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);
}
Aggregations