:::success
# AS Lab 4 - (IAM) Identity and Access Management
:::
## 1. Create corresponding clients and enable Authorization services
:::info
`app-trainer` - It displays data taken from `api-trainer`. You have already configured it in the previous lab, but for this lab make sure that user will have `readonly role` for `api-pokemon` in token claims.
:::
<center>

Figure 1 - Read-only role for Ash
</center>
:::info
Now you need to deal with the client, resources & scopes.
:::
To do this, we will create a client with a confidential type, be sure to enable authorization.
<center>

Figure 2 - Toggle switch "Authorization Enabled"
</center>
As indicated in the text of the laboratory work, I manually created all the necessary scopes.
> scopes (all scopes should be created manually):
>
> deck_create:create
> deck_list:read
> deck:read
> deck:write
> deck:delete
<center>

Figure 3 - New Scopes
</center>
After that, I created a resource. When creating a resource, you can establish an associative relationship with a specific scopes, following the description of the resource from the laboratory work, I added an association with the deck creation scope.
> deck_create
>- represents deck creation capabilities only
>- should be created manually
<center>

Figure 4 - Created a resource, added an scope to it
</center>
## 2. Implement authorization rules
:::info
You can skip all preparation part but do not forget to change config in keycloak.json with config from Installation section
:::
<center>

Figure 5 - Installation section
</center>
:::info
Create necessary policies and permissions for rules:
- any user with role trainer within api-trainer can create deck
- only owner can read deck_list
- only owner can access deck (read, write, delete)
:::
I have previously created the role of a coach, this role is owned by the user Ash.
<center>

Figure 6 - Api-trainer role
</center>
We went to the Policies, selected a Policy for the Role from the drop-down list, created a rule for the role of a **trainer** from the **api-trainer**.
<center>

Figure 7 - New Policy
</center>
In the Permissions tab, I saw that it is possible to create a permit based on a resource.
<center>

Figure 7 - New Permission
</center>
> Hint
The “only owner” policy can be implemented as a JS type policy like that:
```
var permission = $evaluation.getPermission();
var identity = $evaluation.getContext().getIdentity();
var resource = permission.getResource();
if (resource) {
if (resource.getOwner().equals(identity.getId())) {
$evaluation.grant();
}
}
```
<center>

Figure 8 - Policy for owner
</center>
As with the Policy for the trainer role, I created a Policy for the owner. Now I need to configure based on its Permission (scope-based).
<center>

Figure 9 - Access to Deck

Figure 10 - Read deck_list
</center>
As you can see from the screenshot below, the application is working successfully. Now I can add/change/delete decks in the app-trainer file.
<center>

Figure 11 - Pokemon's Decks
</center>
## User-Managed Access
:::info
3. Demonstrate resource sharing
- share one of the user decks in Account Console and from another user in `app-trainer`
:::
Keycloak provides built-in account console:
```
/realms/as_lab/account/#/resources
```
For this task, I created a new coach - Ash's friend Serena. And her Pokemon deck.
<center>

Figure 12 - New Trainer and her Deck
</center>
Next, I activated the User-Managemed Access switch in the Realm settings and went to the resources page.
<center>

Figure 13 - In this screenshot you can see a large number of test decks
</center>
Now let's make it so that Ash can share his deck of cards with the Seren for the Final Battle. And she, in turn, can add any Pokemon to it.
<center>


Figures 14, 15 - Settings

Figure 16 - Result
</center>
## Audit
:::info
Learn about Keycloak audit capabilities and briefly demonstrate some of them that may be handful in incident response.
:::
Let's start with examples from the [documentation](https://wjw465150.gitbooks.io/keycloak-documentation/content/server_admin/topics/events/login.html).
To enable logging of information, it is necessary to activate event saving. This can be done as shown in the screenshot below. I have enabled all events for tracking.
<center>

Figure 17 - Configure Logs
</center>
> The `Saved Types` field allows you to specify which event types you want to store in the event store. The `Clear events` button allows you to delete all the events in the database. The `Expiration` field allows you to specify how long you want to keep events stored.
In the example below, you can see what the account re-login events look like (a new session using a password/login)
<center>

Figure 18 - Example
</center>
It's all fun, but let's set up an email notification to the user in case someone tries to log into his account with an incorrect password. I am not sure that I will thoroughly show every step in the screenshots, however, I will explain the logic of my actions in the text. It's really cool to see when everything works! :D
So, for this we need to do a few things:
1. **Add a mailing address to the administrator**
2. **Set the necessary mail client settings for AS_Lab Realm**
3. **Add wiretapping in logs and mail for the user**
I use my Google mail for these purposes (please don't hack it, why do you need a whole box of junk spam and my Hackmd lab reports?). First you need to add it to the administrator's personal data.
<center>

Figure 19 - Admin Profile
</center>
Then you need to go to the section of Unreliable applications in your Google Account and register a Keycloak in it.
<center>

Figure 20 - Unreliable applications
</center>
Now that I have the password from the application, I can go to the mail client settings.
<center>

Figure 21 - Realm Email tab
</center>
As a host, I use a host for Gmail accounts (smtp.gmail.com). As a port, I use 465 for SSL (below you will also need to activate the switch for this). And then we come up with a test email address (keycloak_test0@gmail.com). After a successful test, a corresponding letter will be sent to the administrator's mailbox.
<center>

Figure 22 - Gmail testing
</center>
Now we will add a listening condition "email", which will send a message to the user in such cases as:
* Login Error
* Update Password
* Update TOTP
* Remove TOTP
<center>

Figure 23 - Event Listeners
</center>
Now let's add an email address for the user. How good is Temp mail from mail.ru.
<center>

Figure 24 - User Profile
</center>
Let's try to enter the password for the Ash incorrectly in the application.
<center>


Figures 25, 26 - Login/pass Error
</center>
And we will see that the user really received an email that someone tried to log into his account using the wrong password.
<center>

Figure 27 - Magic is real
</center>
<center>

Figure 28 - Reset Pass testing

Figure 29 - Email
</center>
## Bonus: UMA 2.0 protocol
:::info
5. Learn about UMA, its main concepts and flows
:::
First, get familiar with the concepts of UMA grant flow:
**a) What is protection API token?**
Protection API Token (or PAT) - is simply an OAuth access token with a particular scope, standardized by UMA with the name uma_protection (it should be available as one of the roles associated with your resource server).
> When you create a resource server, SSO automatically creates a role, uma_protection, for the corresponding client application and associates it with the client’s service account.
<center>

Figure 30 - Example og uma_protection role for api-trainer
</center>
*reference:*
*1.[RedHat SSO about PAT/AAT/etc](https://access.redhat.com/documentation/en-us/redhatsinglesign-on/7.1/html/authorizationservicesguide/serviceoverview)*
**b) What is permission ticket?**
A permission ticket is a special security token type representing a permission request.
> A correlation handle that is conveyed from an authorization server to a resource server, from a resource server to a client, and ultimately from a client back to an authorization server, to enable the authorization server to assess the correct policies to apply to a request for authorization data.
The resolution endpoint provides the resource server with a means to request permission when a client's request for a resource is not accompanied by a requester token (RPT) or is accompanied by an invalid RPT.
A permission is an identifier of a resource and its corresponding areas. In a single instance, the resource server can request permissions only to access resources belonging to the same resource owner, protected by a single authorization server. As a response, the resource server receives a permission ticket representing the same permissions that the resource server requests.
**c) How does resource server create permission ticket?**
The resource server uses the POST method at the resolution endpoint. The body of the HTTP request message contains a JSON object to request permission for a single resource identifier or an array of one or more objects to request permissions for the corresponding number of resource identifiers. The **resource_id** and **resource_scopes** must be defined in the request.
> **resource_id**
> The identifier for a resource to which the resource server is requesting a permission on behalf of the client. The identifier must correspond to a resource that was previously registered.
> **resource_scopes**
> An array referencing zero or more identifiers of scopes to which the resource server is requesting access for this resource on behalf of the client. Each scope identifier must correspond to a scope that was previously registered by this resource server for the referenced resource.
*reference:
2. [Service Protection Permission](https://github.com/keycloak/keycloak-documentation/blob/main/authorizationservices/topics/service-protection-permission-api-papi.adoc)*
**d) How does client use permission ticket?**
The client requests a protected resource without providing an access token. The resource server responds to the client's resource request without a token (at this stage, a permission ticket is received from the authorization server). His response contains the WWW-Authenticate header with the UMA authentication scheme, the publisher URI from the authorization server discovery document in the as_uri parameter, and the permission ticket in the ticket parameter.
And after that, the client requires the issuance of an RPT from the token endpoint. At this point, we assume that the client has received the authorization ticket and the authorization server location from the resource server. Claims can be sent at this endpoint. This is how the main use case of the ticket looks like.
*reference:
3. [UMA Documentation: Flow Details ](https://docs.kantarainitiative.org/uma/wg/oauth-uma-grant-2.0-09.html#protocol-flow-details-sec)*
**e) What should authorization server do with permission ticket?**
If I understood everything correctly, then the authorization server accepts a request from the client for RPT authorization. And then the client redirects the requesting side of the end user to the endpoint of the authorization server claims interaction for one or more interactive approval collection processes in accordance with the requirements of the authorization server. And the client can initiate this redirection immediately after receiving the initial permission ticket from the resource server. In this case, we assume that the authorization server has statically announced its endpoint of the claims interaction in advance in its discovery document.
In short, with a ticket, the authorization server can immediately redirect the client side to the endpoint to interactive collect the necessary claims.
references:
4. [UMA Documentation: UMAFedAuthz](https://docs.kantarainitiative.org/uma/wg/oauth-uma-federated-authz-2.0-09.html#rfc.section.4.1)
**f) What is RPT?**
A Requester Token (RPT) or a special security token that can be requested by client applications using the UMA protocol from a specific endpoint. This token consists of all the permissions granted to a user as a result of the evaluation of the permissions and authorization policies associated with the resources being requested. With an RPT, client applications can gain access to protected resources at the resource server.