100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Allow basic auth clients to get identity info (user and roles)
Rich Turner4252cf119511
diff --git a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.javaindex 46573c6ab..c9093cabb 100644--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java@@ -33,10 +33,12 @@ import org.openremote.model.security.UserResource;import javax.ws.rs.BeanParam;import javax.ws.rs.ClientErrorException;+import javax.ws.rs.ForbiddenException;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;import java.util.ArrayList;import java.util.List;+import java.util.Objects;import java.util.ResourceBundle;import static javax.ws.rs.core.Response.Status.BAD_REQUEST;@@ -64,6 +66,10 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic User get(RequestParams requestParams, String realm, String userId) {+ if (!isSuperUser() && !Objects.equals(getUserId(), userId)) {+ throw new ForbiddenException("Regular users can only retrieve their own roles");+ }+try {return identityService.getIdentityProvider().getUser(new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId@@ -75,6 +81,14 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource}}+ @Override+ public User getCurrent(RequestParams requestParams) {+ if (!isAuthenticated()) {+ throw new ForbiddenException("Must be authenticated");+ }+ return get(requestParams, getRequestRealm(), getUserId());+ }+@Overridepublic void update(RequestParams requestParams, String realm, String userId, User user) {ConstraintViolationReport violationReport;@@ -151,6 +165,10 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic Role[] getRoles(@BeanParam RequestParams requestParams, String realm, String userId) {+ if (!isSuperUser() && !Objects.equals(getUserId(), userId)) {+ throw new ForbiddenException("Regular users can only retrieve their own roles");+ }+try {return identityService.getIdentityProvider().getRoles(new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId@@ -162,6 +180,14 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource}}+ @Override+ public Role[] getCurrentUserRoles(RequestParams requestParams) {+ if (!isAuthenticated()) {+ throw new ForbiddenException("Must be authenticated");+ }+ return getRoles(requestParams, getRequestRealm(), getUserId());+ }+@Overridepublic void updateRoles(@BeanParam RequestParams requestParams, String realm, String userId, Role[] roles) {try {diff --git a/model/src/main/java/org/openremote/model/security/UserResource.java b/model/src/main/java/org/openremote/model/security/UserResource.javaindex d886156e2..1092bdfd1 100644--- a/model/src/main/java/org/openremote/model/security/UserResource.java+++ b/model/src/main/java/org/openremote/model/security/UserResource.java@@ -31,12 +31,9 @@ import javax.ws.rs.*;import static javax.ws.rs.core.MediaType.APPLICATION_JSON;/**- * Manage users in realms.- * <p>- * All operations can only be called by the superuser.- * <p>- * TODO Relax permissions to allow regular users to maintain their own realm+ * Manage users in realms and get info of current user.*/+// TODO Relax permissions to allow regular users to maintain their own realm@Path("user")@JsType(isNative = true)public interface UserResource {@@ -53,10 +50,15 @@ public interface UserResource {@Path("{realm}/{userId}")@Produces(APPLICATION_JSON)@SuccessStatusCode(200)- @RolesAllowed(Constants.READ_ADMIN_ROLE)@SuppressWarnings("unusable-by-js")User get(@BeanParam RequestParams requestParams, @PathParam("realm") String realm, @PathParam("userId") String userId);+ @GET+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @SuppressWarnings("unusable-by-js")+ User getCurrent(@BeanParam RequestParams requestParams);+@PUT@Path("{realm}/{userId}")@Consumes(APPLICATION_JSON)@@ -96,12 +98,18 @@ public interface UserResource {@Path("{realm}/{userId}/role")@Produces(APPLICATION_JSON)@SuccessStatusCode(200)- @RolesAllowed(Constants.READ_ADMIN_ROLE)@SuppressWarnings("unusable-by-js")Role[] getRoles(@BeanParam RequestParams requestParams, @PathParam("realm") String realm, @PathParam("userId") String userId);+ @GET+ @Path("role")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @SuppressWarnings("unusable-by-js")+ Role[] getCurrentUserRoles(@BeanParam RequestParams requestParams);+@PUT- @Path("{realm}/{userId}/role")+ @Path("{realm}/role/{userId}")@Consumes(APPLICATION_JSON)@SuccessStatusCode(204)@RolesAllowed(Constants.WRITE_ADMIN_ROLE)diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex ed477c01e..950fad356 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -11,7 +11,9 @@ import {AssetDescriptor,AttributeDescriptor,AttributeValueDescriptor,- MetaItemDescriptor+ MetaItemDescriptor,+ User,+ Role} from "@openremote/model";import * as Util from "./util";import orIconSet from "./or-icon-set";@@ -367,18 +369,22 @@ export class Manager implements EventProviderFactory {return this._config;}- get roles() {- if (!this._keycloak || !this._keycloak.resourceAccess) {- return [];+ get roles(): string[] {+ if (this._keycloak) {+ if (this._keycloak.resourceAccess) {+ let roles: string[];+ if (this._config.clientId && this._keycloak!.resourceAccess.hasOwnProperty(this._config.clientId)) {+ roles = this._keycloak!.resourceAccess[this._config.clientId].roles;+ } else {+ roles = this._keycloak!.resourceAccess.account.roles;+ }+ return roles || [];+ }+ } else if (this._basicIdentity && this._basicIdentity.roles) {+ return this._basicIdentity.roles.map((r) => r.name!);}- let roles: String[];- if (this._config.clientId && this._keycloak!.resourceAccess.hasOwnProperty(this._config.clientId)) {- roles = this._keycloak!.resourceAccess[this._config.clientId].roles;- } else {- roles = this._keycloak!.resourceAccess.account.roles;- }- return roles || [];+ return [];}get managerVersion() {@@ -504,7 +510,11 @@ export class Manager implements EventProviderFactory {private _name: string = "";private _username: string = "";private _keycloak?: Keycloak;- private _basicToken?: string;+ private _basicIdentity?: {+ token: string | undefined,+ user: User | undefined,+ roles: Role[] | undefined+ };private _keycloakUpdateTokenInterval?: number = undefined;private _managerVersion: string = "";private _listeners: EventCallback[] = [];@@ -798,8 +808,8 @@ export class Manager implements EventProviderFactory {}const options = redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : null;this._keycloak.logout(options);- } else if (this._basicToken) {- this._basicToken = undefined;+ } else if (this._basicIdentity) {+ this._basicIdentity = undefined;if (redirectUrl) {window.location.href = redirectUrl;} else {@@ -864,7 +874,11 @@ export class Manager implements EventProviderFactory {};let authenticated = false;- const url = this.config.managerUrl + "/api/" + this.config.realm + "/asset/user/current";+ this._basicIdentity = {+ roles: undefined,+ token: undefined,+ user: undefined+ };while (!authenticated) {result = await this.config.basicLoginProvider(result.username, result.password);@@ -881,24 +895,27 @@ export class Manager implements EventProviderFactory {continue;}- const response = await fetch(url, {- method: "GET",- credentials: "include",- headers: {- Authorization: "Basic " + btoa(result.username + ":" + result.password)- }- });+ // Update basic token so we can use rest api to make calls+ this._basicIdentity!.token = btoa(result.username + ":" + result.password);+ const userResponse = await rest.api.UserResource.getCurrent();+ const status = userResponse.status;- const status = response.status;if (status === 200) {console.log("Basic authentication successful");authenticated = true;- this._basicToken = btoa(result.username + ":" + result.password);+ this._basicIdentity!.user = userResponse.data;++ // Get user roles+ const rolesResponse = await rest.api.UserResource.getCurrentUserRoles();+ this._basicIdentity!.roles = rolesResponse.data;+// Undertow incorrectly returns 403 when no authorization header and a 401 when it is set and not valid} else if (status === 401 || status === 403) {console.log("Basic authentication invalid credentials, trying again");+ this._basicIdentity = undefined;} else {console.log("Unkown response so aborting");+ this._basicIdentity = undefined;break;}}@@ -934,26 +951,26 @@ export class Manager implements EventProviderFactory {}public getAuthorizationHeader(): string | undefined {- if (this._keycloak && this.authenticated) {+ if (this._keycloak) {return "Bearer " + this._keycloak.token;}- if (this._basicToken && this.authenticated) {- return "Basic " + this._basicToken;+ if (this.getBasicToken()) {+ return "Basic " + this.getBasicToken();}return undefined;}public getKeycloakToken(): string | undefined {- if (this._keycloak && this.authenticated) {+ if (this._keycloak) {return this._keycloak.token;}return undefined;}public getBasicToken(): string | undefined {- return this._basicToken;+ return this._basicIdentity ? this._basicIdentity.token : undefined;}public getRealm(): string | undefined {