use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.
the class AuthorizationTokenService method createAuthorizationResponse.
private AuthorizationResponse createAuthorizationResponse(KeycloakIdentity identity, Collection<Permission> entitlements, KeycloakAuthorizationRequest request, ClientModel targetClient) {
KeycloakSession keycloakSession = request.getKeycloakSession();
AccessToken accessToken = identity.getAccessToken();
RealmModel realm = request.getRealm();
UserSessionProvider sessions = keycloakSession.sessions();
UserSessionModel userSessionModel;
if (accessToken.getSessionState() == null) {
// Create temporary (request-scoped) transient session
UserModel user = TokenManager.lookupUserFromStatelessToken(keycloakSession, realm, accessToken);
userSessionModel = sessions.createUserSession(KeycloakModelUtils.generateId(), realm, user, user.getUsername(), request.getClientConnection().getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
} else {
userSessionModel = sessions.getUserSession(realm, accessToken.getSessionState());
if (userSessionModel == null) {
userSessionModel = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
}
}
ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
AuthenticatedClientSessionModel clientSession = userSessionModel.getAuthenticatedClientSessionByClient(targetClient.getId());
ClientSessionContext clientSessionCtx;
if (clientSession == null) {
RootAuthenticationSessionModel rootAuthSession = keycloakSession.authenticationSessions().getRootAuthenticationSession(realm, userSessionModel.getId());
if (rootAuthSession == null) {
if (userSessionModel.getUser().getServiceAccountClientLink() == null) {
rootAuthSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(realm, userSessionModel.getId());
} else {
// if the user session is associated with a service account
rootAuthSession = new AuthenticationSessionManager(keycloakSession).createAuthenticationSession(realm, false);
}
}
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(targetClient);
authSession.setAuthenticatedUser(userSessionModel.getUser());
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(keycloakSession.getContext().getUri().getBaseUri(), realm.getName()));
AuthenticationManager.setClientScopesInSession(authSession);
clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSessionModel, authSession);
} else {
clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession);
}
TokenManager tokenManager = request.getTokenManager();
EventBuilder event = request.getEvent();
AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, keycloakSession, userSessionModel, clientSessionCtx).generateAccessToken();
AccessToken rpt = responseBuilder.getAccessToken();
Authorization authorization = new Authorization();
authorization.setPermissions(entitlements);
rpt.setAuthorization(authorization);
if (accessToken.getSessionState() == null) {
// Skip generating refresh token for accessToken without sessionState claim. This is "stateless" accessToken not pointing to any real persistent userSession
rpt.setSessionState(null);
} else {
if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
responseBuilder.generateRefreshToken();
RefreshToken refreshToken = responseBuilder.getRefreshToken();
refreshToken.issuedFor(client.getClientId());
refreshToken.setAuthorization(authorization);
}
}
if (!rpt.hasAudience(targetClient.getClientId())) {
rpt.audience(targetClient.getClientId());
}
return new AuthorizationResponse(responseBuilder.build(), isUpgraded(request, authorization));
}
use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.
the class ConflictingScopePermissionTest method getEntitlements.
private Collection<Permission> getEntitlements(String username, String password) {
AuthzClient authzClient = getAuthzClient();
AuthorizationResponse response = authzClient.authorization(username, password).authorize();
AccessToken accessToken;
try {
accessToken = new JWSInput(response.getToken()).readJsonContent(AccessToken.class);
} catch (JWSInputException cause) {
throw new RuntimeException("Failed to deserialize RPT", cause);
}
AccessToken.Authorization authorization = accessToken.getAuthorization();
assertNotNull("RPT does not contain any authorization data", authorization);
return authorization.getPermissions();
}
use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.
the class UserManagedPermissionServiceTest method testUserManagedPermission.
@Test
public void testUserManagedPermission() {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setName("Resource A");
resource.setOwnerManagedAccess(true);
resource.setOwner("marta");
resource.addScope("Scope A", "Scope B", "Scope C");
resource = getAuthzClient().protection().resource().create(resource);
UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
permission.setName("Custom User-Managed Permission");
permission.setDescription("Users from specific roles are allowed to access");
permission.addScope("Scope A");
permission.addRole("role_a");
ProtectionResource protection = getAuthzClient().protection("marta", "password");
permission = protection.policy(resource.getId()).create(permission);
AuthorizationResource authorization = getAuthzClient().authorization("kolo", "password");
AuthorizationRequest request = new AuthorizationRequest();
request.addPermission(resource.getId(), "Scope A");
AuthorizationResponse authzResponse = authorization.authorize(request);
assertNotNull(authzResponse);
permission.removeRole("role_a");
permission.addRole("role_b");
protection.policy(resource.getId()).update(permission);
try {
authorization.authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
try {
getAuthzClient().authorization("alice", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
permission.addRole("role_a");
protection.policy(resource.getId()).update(permission);
authzResponse = authorization.authorize(request);
assertNotNull(authzResponse);
protection.policy(resource.getId()).delete(permission.getId());
try {
authorization.authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
try {
getAuthzClient().protection("marta", "password").policy(resource.getId()).findById(permission.getId());
fail("Permission must not exist");
} catch (Exception e) {
assertEquals(404, HttpResponseException.class.cast(e.getCause()).getStatusCode());
}
// create a user based permission, where only selected users are allowed access to the resource.
permission = new UmaPermissionRepresentation();
permission.setName("Custom User-Managed Permission");
permission.setDescription("Specific users are allowed access to the resource");
permission.addScope("Scope A");
permission.addUser("alice");
protection.policy(resource.getId()).create(permission);
// alice should be able to access the resource with the updated permission.
authzResponse = getAuthzClient().authorization("alice", "password").authorize(request);
assertNotNull(authzResponse);
// kolo shouldn't be able to access the resource with the updated permission.
try {
authorization.authorize(request);
fail("User should not have permission to access the protected resource");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
}
use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.
the class UserManagedPermissionServiceTest method testGrantRequestedScopesOnly.
@Test
public void testGrantRequestedScopesOnly() {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setName(UUID.randomUUID().toString());
resource.setOwnerManagedAccess(true);
resource.setOwner("marta");
resource.addScope("view", "delete");
ProtectionResource protection = getAuthzClient().protection("marta", "password");
resource = protection.resource().create(resource);
UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
permission.setName("Custom User-Managed Permission");
permission.addScope("view");
permission.addUser("kolo");
permission = protection.policy(resource.getId()).create(permission);
AuthorizationRequest request = new AuthorizationRequest();
request.addPermission(resource.getId(), "view");
AuthorizationResponse response = getAuthzClient().authorization("kolo", "password").authorize(request);
AccessToken rpt = toAccessToken(response.getToken());
Collection<Permission> permissions = rpt.getAuthorization().getPermissions();
assertPermissions(permissions, resource.getId(), "view");
assertTrue(permissions.isEmpty());
request = new AuthorizationRequest();
request.addPermission(resource.getId(), "delete");
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
request = new AuthorizationRequest();
request.addPermission(resource.getId(), "delete");
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
request = new AuthorizationRequest();
request.addPermission(resource.getId());
response = getAuthzClient().authorization("kolo", "password").authorize(request);
rpt = toAccessToken(response.getToken());
permissions = rpt.getAuthorization().getPermissions();
assertPermissions(permissions, resource.getId(), "view");
assertTrue(permissions.isEmpty());
}
use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.
the class UserManagedPermissionServiceTest method testPermissionInAdditionToUserGrantedPermission.
@Test
public void testPermissionInAdditionToUserGrantedPermission() {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setName("Resource A");
resource.setOwnerManagedAccess(true);
resource.setOwner("marta");
resource.addScope("Scope A", "Scope B", "Scope C");
resource = getAuthzClient().protection().resource().create(resource);
PermissionResponse ticketResponse = getAuthzClient().protection().permission().create(new PermissionRequest(resource.getId(), "Scope A"));
AuthorizationRequest request = new AuthorizationRequest();
request.setTicket(ticketResponse.getTicket());
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
assertTrue(e.getMessage().contains("request_submitted"));
}
List<PermissionTicketRepresentation> tickets = getAuthzClient().protection().permission().findByResource(resource.getId());
assertEquals(1, tickets.size());
PermissionTicketRepresentation ticket = tickets.get(0);
ticket.setGranted(true);
getAuthzClient().protection().permission().update(ticket);
AuthorizationResponse authzResponse = getAuthzClient().authorization("kolo", "password").authorize(request);
assertNotNull(authzResponse);
UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
permission.setName("Custom User-Managed Permission");
permission.addScope("Scope A");
permission.addRole("role_a");
ProtectionResource protection = getAuthzClient().protection("marta", "password");
permission = protection.policy(resource.getId()).create(permission);
getAuthzClient().authorization("kolo", "password").authorize(request);
ticket.setGranted(false);
getAuthzClient().protection().permission().update(ticket);
getAuthzClient().authorization("kolo", "password").authorize(request);
permission = getAuthzClient().protection("marta", "password").policy(resource.getId()).findById(permission.getId());
assertNotNull(permission);
permission.removeRole("role_a");
permission.addRole("role_b");
getAuthzClient().protection("marta", "password").policy(resource.getId()).update(permission);
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
request = new AuthorizationRequest();
request.addPermission(resource.getId());
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
getAuthzClient().protection("marta", "password").policy(resource.getId()).delete(permission.getId());
try {
getAuthzClient().authorization("kolo", "password").authorize(request);
fail("User should not have permission");
} catch (Exception e) {
assertTrue(AuthorizationDeniedException.class.isInstance(e));
}
}
Aggregations