i have a scenario where i want to restrict the user in keycloak
i have user
user can have access to multiple accounts
in multiple accounts, use can be Admin or agent (reader)
user
|
|
|-------account-1
| |
| |-------admin
|-------account-2
| |
| |-------agent
How can we map this in Keycloak with Policy, Permission, and role?
any reference document any example really helpful
also based from : Resources, scopes, permissions and policies in keycloak
From the answer of Andy, i have created one resource Account and role admin & agent.
created same policies as in example.
i am looking forward to add scopes (auth scope) and roles to JWT token how to map that part so that API gateway or service can verify further.
#changa, I've rewritten my answer based on our discussion. Hope this helps!
Let me first clarify some key areas before I answer. My main focus on the answer that you've linked was really on how to play around the Evaluate tool and I didn't really dive too deeply into some of the concepts - so let's do that :)
In Keycloak, you'll encounter Client and Authorization Scopes. For a formal definition of these terms please check out the Core Concepts and Terms in the Server Administration Guide, but simply put:
Client Scopes are scopes which are granted to clients when they are requested via the scope parameter (once the resource owner permits it). Note that there's also the concept of Default Client Scope but I've chosen to keep things simple. Furthermore, you can leverage protocol and role scope mappers to tailor what claims and assertions are present in the access token.
Authorization Scopes on the other hand are granted to clients after successful evaluation of the policies against a protected resource. These scopes are not granted to clients based on user consent.
The key differences between the two is really when and how a client obtains these scopes. To help you visualize all of this, here's a scenario:
A renowned martial artist called Bob authenticates via Keycloak
Bob get presented with a consent screen where he is asked to share his name, his fighting style and his age.
Bob chooses to give access to his name and fighting style but he declines to share his age.
When we inspect the token now, we would see the following (completely made up) entries for the scope attribute of the access token: name and fighting_style.
Additionally, let's assume that we've set up a couple of protocol mappers (e.g. User Attribute Mapper Type - there are a ton) to display the values for full name and fighting style via the following token claims: fighter_name and martial_arts when the two Client Scopes above are present in the access token. In addition to two previously mentioned scopes, we would also see something like fighter_name: Robert Richards and martial_arts: Freestyle Karate when examining the access token.
Side Note: Given the length of this answer, I've decided to skip this topic but please check out this awesome video at around the 7 minute mark along with the associated GitHub Project for more information. The README is pretty good.
Additionally, let's assume that Bob is mapped to a realm role called Contestant and a client role of Fighter and we did place any restrictions in Keycloak when it comes to sharing this info. So in addition to all the things mentioned above, we would see that information inside the token as well.
Needless to say, this is an oversimplification on my part as I'm simply setting up the stage for demo. purposes and there's much more information inside the access token.
Bob doesn't like how the tournament bracket is laid out as he's eager to fight the world champ as soon as possible, so he attempts to change his placement by sending a request against tournament/tekken6/bracket/{id}. This resource is associated with the scope bracket:modify. Additionally, there is a permission which associates the resource in question with a role based policy named Referee Role Required. If Bob were a Referee then he would be granted the bracket:modify scope but since he isn't, then he is denied that scope.
I've barely touched the surface when it comes to the inner workings of the Authorization process in Keycloak. For more information, check out this practical guide. You can do some pretty cool stuff with UMA.
Ok, so that's enough theory. Let's set up our environment to demo all of this. I'm using the following:
A realm called demo
A client called my-demo-client
A client scope called client_roles
2 users - paul and law
Two realms level roles - Admin and Reader
Two client level roles - demo-admin and demo-reader
Please note that I will using Keycloak 12.0.4 and I will skip almost all the basic setup instructions. I will only share the relevant bits. If you're not sure how to set this all up, please check out the Getting Started Guide or this answer. The answer contains steps for version 8 but the differences are very minor as far as I could tell.
Associating Users And Roles
In order to associate paul with the Admin, Reader, bank-admin and bank-reader roles, please do the following:
Click on Users > View all users > Click on the ID value for paul > Click on Role Mappings > Under Realm Roles move Admin and Reader under Assigned Roles > Select my-demo-client under the Client Roles select box and move demo-admin and demo-reader under Assigned Roles like so
As for law we'll just associate him with Reader and bank-reader.
Associating a client scope with a client
Create a Client Scope by:
Clicking on the Client Scopes link on the left > Click on Create > Enter custom-client-scope for the Name field and Hit Save. It should look like this
Click on Clients on the left > Select the my-demo-client > Click on the Client Scopes tab at the top > and let's just move it to Assigned Default Client Scopes for convenience.
Inspecting the Access Token
We can easily generate an access token for our setup via Keycloak to see what it looks like. In order to do so:
Click on Evaluate tab under Client Scopes.
Select paul as the user
Click on the blue Evaluate button
Click on Generated Access Token. While inspecting the token, look for:
resource_access to see client level roles associated with paul
realm_access to see paul's realm level roles
scope to see the Client Scope that we created called custom-client-scope
If you generate a token for law, you would see less roles when compared to paul.
Obtaining a Scope After Policy Evaluation
Continuing with our setup:
I've created an account/{id} resource with two Authorization Scopes called account:read and account:modify like so
Additionally, I've created two role based policies called Only Reader Role Policy and Only Admin Role Policy where the former requires the Reader realm role while the latter requires the Admin realm role. Here's an example for reference.
Note that you can further enhance that policy at the client level if you wish but to keep things simple, I chose not to do so.
Furthermore, I've created two scoped based permissions called Read Account Scope Permission and Modify Account Scope Permission.
The Read Account Scope Permission will grant the account:read Authorization Scope if the user is either an Admin or a Reader. One key thing to notice here is the the Decision Strategy has to be set to Affirmative in order to achieve this behavior.
Modify Account Permission on the other hand grants the account:modify Authorization Scope to users with the Admin role.
Now, if you choose the evaluate the user paul (remember he is both Admin and Reader) against the Account Resource, he will be granted both the account:read and account:modify Authorization Scopes. Let's see if this true. Here's our Evaluate screen and notice that I did not associate any roles with paul since this was already done via the Users > Role Mappings tab
And here are the results of that evaluation as predicted
Here is the evaluation result for law. Since he's not an Admin he'll be denied the account:modify scope but he'll be granted the account:read scope.
And finally, we can further confirm this by click on Show Authorization Data which shows the permissions inside the access token for law
Hopefully this helps you see where each piece of the puzzle fits in your architecture. Cheers!
Related
I have 2 Keycloak instances:
KC1 which is the main Keycloak for my app
KC2 which acts as an IDP (linked to KC1 via SAML protocol)
I'm trying to retrieve users info (email, name and roles, mainly) in KC1 whenever a SSO user (from KC2) connects to my app. As far as I understand this should be done via IDP mappers.
I tried creating multiple ones with the "Attribute Importer" type with no success. The main problem is that attribute name fields are just textboxes. I don't know where to look to get the correct value I should enter here. For instance for email I tried multiple things like "email", "emailAddress", "mail", etc.. (with all possible cases, i.e. all uppercase, all lowercase, camelcase, etc.) but this is just guess work.
Is there a table somewhere telling what we should enter here? Or at least some way to see what is being sent in the claims (everything is very auto-magic so it's hard to know what's going on under the hood).
The documentation ( https://www.keycloak.org/docs/latest/server_admin/index.html#_mappers ) mentions that you can put the log level to debug to see the claims. Couldn't see them personally, so not sure about that.
Edit : found the problem for basic info (I had to create client scopes with the correct protocol, in my case SAML, and then bind it in the client on the KC2 side. Then use the SAML attribute name defined in the client scope mapper).
However, I still struggle for the roles. Do I have to create them on the KC1 side as well?
Edit 2 : Solved. For future reference, the roles can be found in the access token (not the ID token like basic user info), but they have to be mapped in KC1 to be visible there.
However, I still struggle for the roles. Do I have to create them on
the KC1 side as well?
You can't simply import the roles from KC2 directly to KC1. Instead, you have to create the roles that you want in KC1, and in the appropriate IDP configuration section (of KC1) create a External Role to Role Mapper:
Where you map the role that the user has on the external IDP (i.e., KC2) to the one that the user should have in the KC1. Do that for every role that you want to map.
For SAML IdP integrations you can try the same idea but using the Advance Attribute to Role mapper:
I have a Vault server where users will log-in using Userpass auth method and making use of kv secret engine.
The structure is like below -
-- user-kv
-- u1
-- u1-secret1
-- u1-secret2
-- u2
-- u2-secret1
-- u2-secret2
-- u3
-- u3-secret1
Here, u1, u2 , u3 are username of the users logged in using Userpass auth.
Now, for each user, I want to allow access to his path only. His path refers to this structure user-kv/<username>/ For example -
u1 --> user-kv/u1/*
u2 --> user-kv/u2/*
u3 --> user-kv/u3/*
and so on....
I am currently doing this by creating a separate policy for each user and and assigning it to him. I believe this is not the right way as when number of users grow, it would be difficult to maintain.
Is there a way to specify the logged-in user's username in the path in a policy. Something like -
path user-kv/{{username}}/* {
capabilities = ["read", "update", "create" ]
}
I have tried with templated policies but it doesn't work.
path user-kv/{{identity.entity.metadata.username}}/*
path user-kv/{{identity.entity.name}}/*
I can do something like user-kv/+/* but that would mean every user would have access to other's path.
Can anyone point out a more elegant way or provide links for further research?
I don't have a Vault running at the moment to check this out, sorry, but I believe that the templated policy you tried should work. The key is to create an identity that is associated (via an alias) with the userpass user. It's been a while since I've done this, so I can't remember the details, but check out the docs: https://www.vaultproject.io/docs/secrets/identity
The basic idea you have is feasible, but it is a lot more complex than that.
First, some background
A user in Vault is called and entity. When you authenticate for the very first time, a Vault entity will be created automatically, unless one already exists.
Obviously, you had to login with some auth backend. Let's say you used LDAP. Whatever you actually used is irrelevant for this discussion.
When you authenticated, an entity alias was created to tie this specific user in that specific auth backend to an entity.
With that background information, here is where it gets complicated.
Vault supports multiple auth backends, and you can tie them all to a single entity. So if our user prefers to login with the Github auth backend, he still keeps his access rights (aka policies). That happens because you would have set the entity alias prior to the user logging in.
Now even if you are using a single auth backend, Vault will still behave like that, because it can't know what the future holds.
Now back to your question.
To allow a path to represent a user, you must use the syntax described here. But to use them, you need to know in advance either:
The name of the entity
The name of the user in the auth backend
Option #2 will also require you to assign multiple policies (one per auth backend). I suggest you go with option 1.
The easiest way to acheive what you want (even if it not that easy) is to provision entities before they log in, and associate metadata to it.
Say you add the metadata kv-user=u3 to the entity that represents the user named u3, Then use {{ identity.entity.metadata.kv-user }} in your policy file.
I have 2 users, one with less than 30 roles and one with 400 roles. When I login with the 30 role user, I can reach the redirect URL without issues. But when I log in with the 400 role user, the request to the redirect URL doesn't complete. If I reduce the number of roles in the 400 role user then it will work. So, is there a way to disable passing roles in the java access token or increase some limit somewhere that's causing the failure?
I would suggest to focus rather on roles reduction/optimization than forcing the transmission (raising limits) over the maximum number of roles inside tokens (or anywhere else).
Some interesting questions (among others) to start with:
Which protected resources am I going to serve?
What am I trying to protect? and what are the associated risks? (build a Threat Model)
How do resources are served by each application? and how are they distributed among my applications?
What kind of resources are they? How can I group them? Which sets are identifiable? or what are the relationships between them? What actions are possible against all sets of resources?
Who are the users of each application? How will they interact with my resources? Which flows are sensitive?
What roles can I define for all my resources?
Which role can apply to each application, resource type or set?
What kind of user groups can I create?
Do I need additional attributes or claims for each set of roles or users/groups?
I firmly believe that if you answer all these questions you will end up having a bunch of roles instead of hundreds. Think security by design and follow principle of least privilege.
Focus on your use case
Now as far as I understand, your blocking point is that you are assuming that each resource is unique, sensitive and requires its own permissions, and consequently a role definition. While it may be true in some cases, in most other cases it does not mean that you have to use the token roles/scopes/claims to secure your assets deep at the resource-level. I'll try to illustrate this sentence by an example.
RBAC and authorizations example for your use case
Let's assume that:
you have millions of sensitive resources to serve
each registered user of your application has access to a (different) set of these resources.
your resources are splitted into, say, 3 categories (e-books, videos, musics).
each resource can be downloaded, uploaded, deleted.
your application will meet unregistered users, registered users, contributors and administrators
registered users will always have read access to resources (not a single action will ever allow a modification)
contributors are particular registered users who can perform special actions including modification ('upload', 'edit')
contributors and administrators may have access to various administrative parts of the application
your application will evolve by serving additional categories of resources in the future and new actions will be available to users later (such as 'flag', 'edit' or 'share link').
Then first things first:
organize your resources accordingly by serving them behind categorized paths such as: .../myapp/res/ebooks, .../myapp/res/videos, .../myapp/res/musics
identify your resources via UUID such that a resource may look like: .../myapp/res/ebooks/duz7327abdhgsd95a
Now imagine that your business risks or at least the greatest risks you wish to avoid are:
unregistered users having gaining access or rights for any part of the application or resource
uncontrolled registration process (robots, spam, no mail verification, fake users, ...)
registered users gaining illegal privileges (unauthorized actions, access to other categories, illegal administrative rights)
discovery of available resources by any mean
You will note that I voluntarily didn't listed:
registered user having illegal access to certain resources. For example: maliciously pointed/provided by an existing user.
This is because it is not a high risk as you may hold contact information about registered users as well as log activity and actions, quota or requests throttling, and you may be able to ban them or start legal action against them. Your registration process is also assumed robust and secure. Nonetheless if its considered a critical risk you can address this with extra mechanisms (cf. suggestions at the end). But never will it result in adding extra roles, such as one per resource, as it does not fit in any security model.
That being said, finally, here are the roles and authorizations scheme you may come with:
SCOPE / AUDIENCE
MY_APP
ROLES
USER
CONTRIBUTOR
ADMINISTRATOR
CLAIMS / ATTRIBUTES
CATEGORIES
ACTIONS
--> POSSIBLE USER GROUPS
USERS
Roles: USER
Claims: CATEGORIES(variable), ACTIONS('download')
CONTRIBUTORS
Roles: USER, CONTRIBUTOR
Claims: CATERGORIES(variable), ACTIONS('download', 'upload', 'edit')
ADMINISTRATORS
Roles: USER, CONTRIBUTOR, ADMINISTRATOR
Claims: CATEGORIES(*), ACTIONS(*)
Following this model, assigning the correct group to each registered user will provide high-grade security by mitigating/controlling the main risks. As claims/attributes are defined in the token(s) (managed and signed by Keycloak) then you can trust this information in your application and serve your resources accordingly and safely. There is also no risk of illegal access or discovery of resources as you are using UUIDs, only registered users having had access once to a resource will know it and registration with appropriate category access will be needed for another user to access it (to only be able to read it basically). Of course you may store in a database the list of resources to which each user has access to, raising the overall security to a very high level.
However, if the latest is not enough you may also implement rolling UUIDs or temporary links for your resources when served to users. To go farther you may also define groups and masks for your categories, resources and actions.
In fine, in this example I made use exclusively of token claims to define roles (common claim), categories and actions (custom claims). In terms of security the authentication and identity will be the first-line security followed by roles then categories, actions and stored list of resources per user (db).
Other alternatives are obviously possible, its just an example. Still, I hope it helps!
To fix this problem you should start from defining client scope mappings for each of you applications (e.g. oidc clients). Main idea of this facility is that even if your user is super duper admin with all existing roles, all of his roles actually don't required for any particular application. For example client foo which defines following roles:
foo_user
foo_viewer
to perform its security logic need to know only whether currently logged user has foo_user or foo_viewer, but it doesn't care about has this user roles bar_user or bar_admin from application bar. So our goal is to make Keycloak return for any client access token with only valuable set of roles for this client. And roles scope mappings is you friend here. You can set for client foo scope like:
foo.foo_user
foo.foo_viewer
bar.bar_admin
and now even if logged user has role "bar.bar_admin" this will not go to access_token since client foo doesn't take this role into account. After applying some scope settings you can test them at 'Clients -> $CLIENT_OIDC_ID -> Client scopes tab -> Evaluate sub tab.
As for you case with 400 roles, i'm quite confident that none of your application requires all of 400 roles, so precise scope configuration for you apllications can drammatically reduce access token size.
But if i'm mistaken and you really have an application that rely on large amount of roles you should look into you runtime settings.
For example if you run keycloak behind reverse proxy like nginx large tokens may not fit in default HTTP parameters buffer size (afaik about 2-4kb) so you have to increase it via appropriate nginx configuration option. Another example is tomcat which has about 16kb as default HTTP header buffer, so if you send request with very large access token in Authorization header Tomcat may not handle this request properly.
I have developed a web application with following architecture:
Frontend : Angular 6
Backend : Java REST APIs with Springboot
I want to add authentication and authorization to it. For that I'm looking for some open source application (e.g. KeyCloak, Gluu etc.). I would like to know in which tool the below scenarios are supported.
There will be predefined set of Activities on UI (e.g. Add, Edit,
Delete etc)
There will be predefined Access Levels (e.g. Read, Write, No Access)
I should be able to create Roles, then assign activities and access levels to those roles and assign those roles to user.
Can you please help me to find out a tool which supports my above scenario?
I tried something for KeyCloak, but i couldn't find a way to add activities, access levels and map roles to it. I think everything there is governed by Role only.
I just realized that I need Activity based authorization and not Role based authorization. Please help me find some tool for that.
I'm not sure what is meant by activity based authorization but i suspect you actually mean permission based authorization, in example: Grant permissions to users to perform certain actions.
Shiro offers you permissions and role based authorization out of the box.
You can create roles, add permissions to these roles and assign them to a user. Supported are implicit and explicit roles, whereas one role can hold any number of permissions. You can even work with wildcards and group the permissions.
For more information you should take a look at the official Shiro entry and especially the web documentation for your project in particular. Shiro offers full support for Spring-Boot applications, you can find a HowTo here.
Shiro fully supports your described scenario.
I'm looking for some deep down detailed information on google's use of oauth scopes
My Drive app is working, so I get the simple use of scopes. However I have the following detailed questions/issues..
I specify scopes twice. Once in my app and then also in the API
Console. What is the respective significance of these two scope
declarations?
If I remove scopes, must my user re-authorise my app, or is this
only required for adding additional scopes?
If the answer to 2, is 'I can't silently remove scopes', will the
Google libraries deal gracefully with re-authorising the user, or
will I just get 403 failures? I've read How should an application add/remove scopes to an existing grant? but the accepted answer specifically references adding scopes, whereas my question is about removing scopes.
Can different modules within my app request different scopes within
the superset specified in the API console? To explain, my app has 3
components: a chrome extension accessing Drive, a web client using
JS to access Drive and YouTube (in online mode), and a server
component which accesses Drive (in offline mode)..
Can my app. enquire what scopes it has been granted?
A general question, I'm sure I face the same dilemma as many app authors. If I increase functionality (a good thing since it attracts users), I also need to increase permissions/trust a user places in my app (a bad thing since it repels users). Are there any recommendations on how apps should best handle this conflict of interests?
List of scopes in your client code - this is what a user authorizes your app to do
When you request authorization from a user, you need to specify what you would like the user to consent to. This is what the list of scopes is used for - it controls the text the user sees when they authorize your application, and the refresh / access tokens granted by that authorization are limited to making API calls that are allowed by those scopes.
List of enabled services in the API Console - this is what your app authorizes users to do
To my knowledge there is no list of scopes specified in the API Console. There is however a list of Google services that can enabled. Enabling/disabling a service here is more about turning on/off ability to make API calls and managing quota and/or accepting terms of service related to that API, than it is authorization.
When an API call is made - you send along an access token
The access token encapsulates the user making the request, the scopes the user authorized you for, and the client ID used for the authorization (which in turn belongs to your project). At this point you need to have the service that the API call is sent to enabled on the project, and the correct scope for the API request - or you will get a 403.
When your list of required scopes changes - you should expect users to need to re-authorize
At the point you request an access token (typically by sending a refresh token) you need to be prepared for that request not to succeed. Maybe it's because you've added scopes - but maybe a user has chosen to visit https://accounts.google.com/IssuedAuthSubTokens and has revoked your applications access. I'm not sure whether if you request less scopes than was granted by the user initially will trigger this, I would experiment to test - but the point is that regardless your code needs to be able to handle this scenario. I believe the OAuth2DecoratorFromClientSecrets (from the linked question) will handle this gracefully for you but am not certain - it should be easy enough to verify.
Using the same authorization across multiple clients - suggest reading through this doc and see if it covers all of your scenarios: https://developers.google.com/accounts/docs/CrossClientAuth
To see scopes granted to an access token - use the OAuth2 API: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=yaxxxxxxxxxxxxxxx