# DPP IAM
## Usage
### Get Admin Token
```
curl -d 'client_id=dpp-frontend' -d 'username=dpp_admin@eecc.de' -d 'password=uePzG4yEGY9x9ANZ5K4pR3myZGn9hI' -d 'grant_type=password' 'https://keycloak.pp.dpp.eecc.de/auth/realms/dpp/protocol/openid-connect/token'
```
## Requirements
Five template products accessible for all MOs.
Each MO may adapt these templates on their own while the access to the modified products is restricted to the MO.
An admin user within each MO may create/invite new users and modify the product.
Other users within the MO may only view the resulting DPP and trigger certain lifecycle actions on the product.
There is a global admin user within the dpp application who may access all ressources.
## Keycloak
There are two instances of keycloak on the eecc k8s cluster:
- PP stage: https://keycloak.pp.dpp.eecc.de/auth
- PROD stage: https://keycloak.dpp.eecc.de/auth
*master realm credentials*
> user: admin
> pw: `kubectl get secret keycloak-admin -o jsonpath="{.data.adminPassword}" | base64 -d`
### Realm
We use the realm `dpp` to separate all DPP relevant IAM ressources from future projects.
### Clients
We use OIDC clients to provide both user authentication and authorization via OAuth2.0 means.
> Create new client:
>
> - KC: Clients -> Create Client -> (1) Client type -> `OpenID Connect`
For the UI we want to force a user to login.
For backend API we do not want it to require user login. Endpoints should only validate the access token.
#### `dpp-frontend`
##### OAuth2.0 params
- OIDC client type: `public client`
- > KC: -> (2) Capability config -> Client authentication -> `OFF`
- OIDC access grant type: `Authorization code grant`
- > KC: -> (2) Capability config -> Authentication Flow -> `Standard flow` (OIDC: grant_type=code) ON, others OFF
- During development `Direct access grant` (OIDC: grant_type=password) can be enabled, which would allow to fetch the access token via username+password directly so you do not need to start the FE project and catch the access token there. Instead fetch the access token via:
```bash
# Eg. fetch token on PP stage
curl -d 'client_id=dpp-frontend' -d 'username=<USER_NAME>' -d 'password=<PASSWORD>' -d 'grant_type=password' 'https://keycloak.pp.dpp.eecc.de/auth/realms/dpp/protocol/openid-connect/token'
```
### Roles
We use _realm roles_ to enable multi tenancy to differentiate users per MO `GS1_X`.
The `DPP` realm role allows access on all ressources.
JWT json path: `$.realm_access.roles`
> Create a realm role:
>
> - KC: Realm roles -> Create role
We use _client roles_ in client `dpp-frontend` to define users within a MO as admin or user.
JWT json path: `$.resource_access.dpp-frontend.roles`
> Create a client role:
>
> - KC: Clients -> `dpp-frontend` -> Roles -> Create role
### Groups
Groups are a keycloak mean to make the assignment of multiple roles to a user more efficient. Users are made members of a (sub)group which defines a set of roles that the user inherits.
> Create a group:
>
> - KC: Groups -> Create Group -> [choose a name]
> - KC: Groups -> `yourGroupName` -> Role mapping -> Assign role
> Make user a group member (i.e. assign him the roles the group defines):
> - KC: Users -> [choose user] -> Groups -> Join Group
> To see the roles the user actually has:
> - KC: Users -> [choose user] -> Role mapping -> [uncheck] `Hide inherited roles`
> To see all group members
> - KC: Groups -> [choose group] -> Members
## User organization
### User profile
- email (mandatory)
We use email as username
> KC: Realm settings -> Login -> Email as username -> ON
> KC: Realm settings -> Login -> Login with email -> ON
### General user structure
```
DPP realm
|
|- Tenant 'DPP' (DPP)
| |
| |- User DPP_admin
| |- User DPP_company
|
|- Tenant 'GS1 Germany' (GS1_GER)
| |
| |- User GS1_GER_admin
| |- User GS1_GER_user_1
| |- ...
| |- User GS1_GER_user_N
|
|- Tenant 'GS1 France' (GS1_FRA)
| |
| |- User GS1_FRA_admin
| |- User GS1_FRA_user_1
| |- ...
| |- User GS1_FRA_user_N
|
|- ...
```
### User permissions
Non technical description
|user type| tenant | role | scope of action | number of users |
|-|-|-|-|-|
|***anonymous***|-|-| access landing page | unknown (users that are not logged in)|
|***DPP_admin***| DPP | admin |in all GS1_X: <br> <ul><li>create/delete product</li><li>edit product masterdata</li><li>view dpp</li><li>create/delete **GS1_X_user**s</li></ul> | one (created by eecc)|
|***DPP_company***| DPP | company |in all GS1_X: <br> <ul><li>perform action on product</li></ul>| multiple (created by eecc)|
|***GS1_X_admin***| GS1_X | admin |in GS1_X:<br> <ul><li>edit product masterdata</li><li>view dpp</li><li>create/delete **GS1_X_user**s</li></ul>| multiple per **GS1_X** tenant (created by eecc) |
|***GS1_X_user***| GS1_X | user |in GS1_X: <ul><li>edit product masterdata</li><li>view dpp</li></ul>| number depends on create/delete from: <br>- ***DPP_admin*** (in case of service request) <br> - **GS1_X_admin** (by regular usage)|
### User KC mappings
Technical description of user permissions in terms of KC means
|user type|group membership| effective realm role | effective client roles |
|-|-|-|-|
|***anonymous***|-|-|-|
|***DPP_admin***|`DPP`, `DPP/admin`|`DPP`| dpp-frontend:<br>`admin`,`user`,`company`<br>realm-management:<br>`manage-users`, `view-users`, `query-users`, `query-groups` |
|***DPP_company***|`DPP`, `DPP/company`|`DPP`| dpp-frontend:<br>`company` |
|***GS1_X_admin***|`GS1_X`, `GS1_X/admin`|`GS1_X`|dpp-frontend:<br>`admin`,`user`<br>realm-management:<br>`manage-users`, `view-users`, `query-users`, `query-groups` |
|***GS1_X_user***|`GS1_X`, `GS1_X/user`|`GS1_X`|dpp-frontend:<br>`user`|
## User management via KC API
In order to enable a user to CRUD a new user within keycloak (via api) that user must have
client roles `manage-users` and `view-users` from client `realm-management`. Both roles further automatically add `query-users`, `query-groups` roles.
These are predefined client roles keycloak uses to determine access on its API. You do not need to create them by yourself.
These roles are inherited via subgroup `DPP/admin` or `GS1_X/admin`.
### Create user
Fetch <YOUR_TOKEN> for that user (double check that it contains `manage-users` role) and create a ***GS1_GER_user*** (email==username) (groups: `GS1_GER`, `GS1_GER/user`) via:
``` bash
curl -X POST \
'keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/users' \
--header 'Accept: */*' \
--header 'Authorization: Bearer <YOUR_TOKEN>' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "test_user@gs1.de",
"groups":["GS1_GER", "GS1_GER/user"],
"enabled": true
}'
```
### Delete user
Fetch user id via user name (i.e. GS1_GER_user)
``` bash
curl -X GET \
'https://keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/users?username=test_user@gs1.de' \
```
Delete user via its id
``` bash
curl -X DELETE \
'https://keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/users/<USER_ID>' \
--header 'Accept: */*' \
--header 'Authorization: Bearer <YOUR_TOKEN>'
```
### Get all users of GS1_X tenant
Fetch group id via group name (i.e. GS1_GER)
``` bash
curl -X GET \
'https://keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/groups?search=GS1_GER' \
```
Get all users in that group (i.e. all users of GS1_GER tenant)
**Note:** To further differentiate admin vs. user users within that tenant you need to fetch group members by the respective subgroup id.
``` bash
curl -X GET \
'https://keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/groups/<GS1_GER_GROUP_ID>/members' \
```
## User registration
**GS1_X_admin** users are created by **DPP_admin** (EECC)
**GS1_X_user** users are created by **GS1_X_admin** users or **DPP_admin** (EECC)
### UX flow
- admin creates a user
- users have an e-mail where they will receive notification to update their password
- Call this to trigger email notification for the recently created user with <USER_ID>
``` bash
curl -X PUT \
'https://keycloak.pp.dpp.eecc.de/auth/admin/realms/dpp/users/<USER_ID>/execute-actions-email?redirect_uri=https%3A%2F%2Fpp.dpp.eecc.de%2F&client_id=dpp-frontend' \
--header 'Accept: */*' \
--header 'Authorization: Bearer <YOUR_TOKEN>' \
--header 'Content-Type: application/json' \
--data-raw '["UPDATE_PASSWORD"]'
```
- they click the link and are redirected to a customized keycloak page where they update their password. Once completed, the dialog contains a link to the DPP application (in the above curl: `redirect_uri=https://pp.dpp.eecc.de`) where the user can log in for the first time.
### Password policy
> KC: Authentication -> Policies -> Password policy
- not: email (i.e. here: username)
- minimal length: 8
### Mail server settings
> KC: Realm Settings -> Email
We use our email server at ionos and send mails from `noreply-dpp@eecc.info`
- From: noreply-dpp@eecc.info
- Host: smtp.ionos.de
- Enable SSL: ON
- Authentication: ON
- Username: `noreply-dpp@eecc.info`
- Password: see keepass
## Theme customization and activation in KC deployments
Themes in keycloak are customized by modifying Freemarker templates.
To activate the theme we need to provide the themes in a container pushed to eecc registry and link it to the helm chart that deploys keykloak in the eecc kubernetes cluster.
### Theme customization
[Keycloak customization guide](https://www.keycloak.org/docs/latest/server_development/#_themes)
Go to https://gitlab.eecc.info/dennis.borrmann/gs1-keycloak-custom-theme and modify the template files according to your needs
These are the basic steps:
- customize the theme templates
- Run `./package.sh`
- builds a jar from the customized templates folder
- Run `./build_push_init_container.sh`
- builds a container image and pushes it to eecc registry
### Theme activation in keycloak pods
Deployment guide: [Keycloakx helm chart](https://github.com/codecentric/helm-charts/tree/master/charts/keycloakx)
Since the theme providing container is now in the repository it can be linked in the helm chart that deploys our keycloak instances.
Go to https://gitlab.eecc.info/eecc-internal/eecc-k8s-helm and checkout the eecc helm collections.
In subfolder `./keycloak` run `update.sh` to activate the theme.
## Spring backend protection (OAuth2 resource server)
We use this library to ease endpoint protection:
https://github.com/ch4mpy/spring-addons/tree/master/spring-addons-starter-oidc
The library allows us to do endpoint protection via properties and spring security annotations only, i.e does not require to parse the jwt token manually.
Since the login/logout is handeled by the frontend we configure our backend as OAuth2 resource server.
**pom.xml dependencies**
``` xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-starter-oidc</artifactId>
<version>7.0.0</version>
</dependency>
```
**Example: application.yml**
``` yml
com:
c4-soft:
springaddons:
oidc:
ops:
- iss: https://keycloak.pp.dpp.eecc.de/auth/realms/dpp
jwk-set-uri: https://keycloak.pp.dpp.eecc.de/auth/realms/dpp/protocol/openid-connect/certs
username-claim: preferred_username
authorities:
- path: $.realm_access.roles
- path: $.resource_access.dpp-frontend.roles
prefix: ROLE_
resourceserver:
permit-all:
- "/public"
cors:
- path: /**
allowed-origin-patterns: http://localhost:8081
```
> - path: $.realm_access.roles
This allows to use `hasAuthority()` Spring security annotations on the endpoints.
Use this to differentiate tenants (DPP, GS1_X)
> - path: $.resource_access.dpp-frontend.roles
> prefix: ROLE_
This allows to use `hasRole(), hasAnyRole()` Spring security annotations on the endpoints.
Use this to differentiate roles (admin, user, company) within tenants (DPP, GS1_X).
**Example: Controller Endpoints**
``` java
// allowed user types: DPP_admin, GS1_GER_admin
@GetMapping()
@PreAuthorize("(hasAuthority('DPP') or hasAuthority('GS1_GER')) and hasRole('admin'))")
String exampleA() {
return "You accessed the admin space of GS1_GER tenant";
}
// allowed user types: DPP_admin, GS1_FRA_admin, GS1_FRA_user
@GetMapping()
@PreAuthorize("(hasAuthority('DPP') or (hasAuthority('GS1_FRA')) and hasAnyRole('admin','user'))")
String exampleB() {
return "You accessed the user space of GS1_FRA tenant";
}
```
## PP/PROD realm synchronization (manually)
In order to synchronize realm configuration (Groups, Roles, Clients, .. ), but NOT user accounts, you can export a realm to a json and import that json in another keycloak instance to create a new realm.
Export PP config:
> KC: Select Realm -> Realm Settings -> Click "Action" Dropdown (top right) -> Partial export (Select all switches)
Import to PROD:
> KC: Create Realm -> Resource file (Select the json from above)