asp.net core / openiddict & client spa Authorization with custom permissions - asp.net-core

I need some help in understanding a basic thing or two with Token-based authentication.
My setup is a backend asp.net core app with openiddict for token auth. It's all working well so far - I now need to add user-permissions. I will have a lot of them (e.g. User can view xy, user can edit xy, user can delete xy, with many different xy-components). Backend is working well so far, my problem is now: How to get these permissions via token to my client side app..
As far as I understood these are not classical "claims" as a claim would describe "who" you are rather "what you are allowed to do" . Right?
But how can I pack them into my id_token/ How can I add them to my payload?
Second thing: Do I need to validate the token (signature) in my case? Every Api-request ist validated at server side, so basically I don't need to care if my client side permissions are tempered with, right? (As they are only for UI-Display purposes)
Thanks for your help!

As far as I understood these are not classical "claims" as a claim would describe "who" you are rather "what you are allowed to do" . Right?
In theory, nothing prevents you from representing permissions as claims, just like you'd do with roles or any other claim. In practice tho', it's rarely the best approach, because the number of actions a user can do is usually important (and often unlimited: can the user A update the product 124? And this other product?).
A possible alternative is to catch the 403 responses returned by your API when a user is not allowed to execute a specific action so you can display an adequate error message. Another one is to create an API endpoint that dynamically determines whether a user is allowed to execute the action, according to your own policy.
Second thing: Do I need to validate the token (signature) in my case? Every Api-request ist validated at server side, so basically I don't need to care if my client side permissions are tempered with, right? (As they are only for UI-Display purposes)
Both access tokens and identity tokens are digitally signed, so they can't be tempered with (at least, not easily). You don't need to validate signatures yourself, as it's already done by the validation/JWT middleware.

Related

Implementing public API keys with microservices

For most client applications and UI approaches JWTs seem to be a good way to carry tokens for an OAuth based approach. This allows decoupling of a User/Auth service and the services that are actually being accessed.
Given this architecture
My question is: in the case of public APIs (ie Github or Slack) where a bearer key is generated with specific roles. How is that key authorized in a microservice architecture? Do those types of keys just require that the Auth service gets queried with every request?
Could an API gateway mitigate this? I would like to understand if a solution exists where there is minimal communication between services. Thank you!
Normally, this is solved using scopes. The scopes are permissions given to a user to do certain operations,for example there will be a scope for read a repository, another for update it, another one for delete etc..
These scopes are tied to the token and normally are requested by the user himself or added automatically depending on the user type. And the same as the authentication process, they could be included in the token itself coded as a claim in a jwt or they could be requested or checked by calling an oauth server when one operation is requested.
The advantages of include them in jwt is that there is not need to call an external server every time an operation is requested so there is a lower latency and less bandwith is required, also you remove a point of failure. Obviously if this solution is used the token must be properly signed or even encrypted to avoid possible manipulations.
However it has also drawbacks, and the most dangerous one is that the token cannot be revoked because this information cannot be included in the token and the service that check if the token is valid only can access the data contained in the token itself. Because of this, this kind of tokens are normally issued with a little expiry time so in case of the token is stolen, the validity of it will be very limited

Handling authorization with IdentityServer4

I'm extremely confused on how to use a centralized IDP with both authentication and authorization. The architecture for my project was to be a single web API and one React client. I wanted to keep things structured out into microservices just to try something more modern, but I'm having major issues with the centralized identity, as many others have.
My goal is fairly simple. User logs in, selects a tenant from a list of tenants that they have access to, and then they are redirected to the client with roles and a "tid" or tenant id claim which is just the GUID of the selected company.
The Microsoft prescribed way to add identity in my scenario is IdentityServer, so I started with that. Everything was smooth sailing until I discovered the inner workings of the tokens. While some others have issues adding permissions, the authorization logic in my application is very simple and roles would suffice. While I would initially be fine with roles refreshing naturally via expiration, they must immediately update whenever my users select a different tenant to "log in" to. However, the problem is that I cannot refresh these claims when the user changes tenants without logging out. Essentially, I tried mixing authorization with authentication and hit a wall.
It seems like I have two options:
Obtain the authorization information from a separate provider, or even an endpoint on the identity server itself, like /user-info but for authorization information. This ends up adding a huge overhead, but the actual boilerplate for the server and for the client is minimal. This is similar to how the OSS version of PolicyServer does it, although I do not know how their paid implementation is. My main problem here is that both the client and resource (API) will need this information. How could I avoid N requests per interaction (where N is the number of resources/clients)?
Implement some sort of custom state and keep a store of users who need their JWTs refreshed. Check these and return some custom response to the caller, which then uses custom js client code to refresh the token on this response. This is a huge theory and, even if it is plausible, still introduces state and kind of invalidates the point of JWTs while requiring a large amount of custom code.
So, I apologize for the long post but this is really irking me. I do not NEED to use IdentityServer or JWTs, but I would like to at least have a React front-end. What options do I have for up-to-date tenancy selection and roles? Right when I was willing to give in and implement an authorization endpoint that returns fresh data, I realized I'd be calling it both at the API and client every request. Even with cached data, that's a lot of overhead just in pure http calls. Is there some alternative solution that would work here? Could I honestly just use a cookie with authorization information that is secure and updated only when necessary?
It becomes confusing when you want to use IdentityServer as-is for user authorization. Keep concerns seperated.
As commented by Dominick Baier:
Yes – we recommend to use IdentityServer for end-user authentication,
federation and API access control.
PolicyServer is our recommendation for user authorization.
Option 1 seems the recommended option. So if you decide to go for option 1:
The OSS version of the PolicyServer will suffice for handling the requests. But instead of using a json config file:
// this sets up the PolicyServer client library and policy provider
// - configuration is loaded from appsettings.json
services.AddPolicyServerClient(Configuration.GetSection("Policy"))
.AddAuthorizationPermissionPolicies();
get the information from an endpoint. Add caching to improve performance.
In order to allow centralized access, you can either create a seperate policy server or extend IdentityServer with user authorization endpoints. Use extension grants to access the user authorization endpoints, because you may want to distinguish between client and api.
The json configuration is local. The new endpoint will need it's own data store where it can read the user claims. In order to allow centralized information, add information about where the permissions can be used. Personally I use the scope to model the permissions, because both client and api know the scope.
Final step is to add admin UI or endpoints to maintain the user authorization.
I ended up using remote gRPC calls for the authorization. You can see more at https://github.com/Perustaja/PermissionServerDemo
I don't like to accept my own answer here but I think my solution and thoughts on it in the repository will be good for anyone thinking about possible solutions to handing stale JWT authorization information.

How can I define policies for my API for two types of access tokens, one with an identity (sub) and one without?

I am using IdentityServer4 via ASPNET Core, and I want users to access my API both by the web browser via their identity (Implicit and Hybrid), and by clients programatically (Client Credentials). I realize all I have to do is add AddIdentityServerAuthentication and I am done. However, that only solves the authentication aspect of this problem, not the authorization.
Authorization:
With ASPNET Core, you can just use Role based auth (or PolicyServer permissions which is similar) but only if you have an identity with role claims, that does not work for client credentials. So that brings us to needing to secure by role, or policies AND by scopes. How can I do this?
You cant have multiple policies, if you do, they both must pass.
You can't have multiple auth schemes, because my call to AddIdentityServerAuthentication will have to use the same authority, so how would IdentityServer4.AccessTokenValidation/JwtBearer know which you scheme challenge you are trying to pass?
Multiple requirements could work, but you need to add extra requirements on the condition that you are dealing with a non-identity access token. How can you detect what type of token you are dealing with? Is it safe to just say "If no sub, this is client creds."
Should I scrap this design and force device code flow on my users? Look at az cli it magically opens a browser, and then you can start scripting away to your hearts content. IS4 supports this with ease, especially with verficationUrlComplete
I think I have a working POC, but I am far from happy with it. https://gist.github.com/VictorioBerra/8c333a228c55d86a7c15f7f300284634
It involves basically re-implementing the default scope claim requirement handler and policyservers permission requirement handler. But thats the only way to conditionally apply the requirement handlers based on the token type.
There are at least a couple of ways of how to go around your problem of implementing role based authentication:
You might have misunderstood the fact that a client can have role claims in the client_credentials flow.
You could even have sub claim if you implemented client_credentials_custom flow and essentially bind a client to a particular user account (think of this as a service account)

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

ASP .NET WebAPI default OWIN authentication - help clear things up

I have some general/how-does-it-work-inside questions about WebAPI and OWIN (specifically, the default configuration which is set up when you create new WebAPI project in VS2013 and select Individual user account authentication). I did that, then I registered (using jQuery post) and even logged in (received token which I included in Authorization header, receiving access to protected resource. I just have some more questions about it:
Are my data stored inside authentication token? I know my password isn't, but is token containing encrypted data, or is just a random string? These are the only 2 options that I can think of: either token contains encrypted data (userId, expiration date, etc.) and server app deciphers it and grants me access to resources, or token is a random string and all user data are stored on server (token is used as a key to obtain correct user data entry). If the second theory is right, the token <-> userData lookup must be stored somewhere - is it session, cache or database maybe?
If i wanted to make a RESTful API, what about Roles, etc. (in general - data beyond simple who-are-you identification that I need for every request)? Again: first thing that comes to mind is to store them inside token. But if the data grows large isn't that too much overhead to send with each request (plus headers themselves probably are limited in size)? Second thing is using external OAuth service (like Facebook or Twitter) - if the user authenticates using external token, I can't control what information does it contain. Alternative is to get the data I need from the database each time, but isn't it bad practice? Every single request would need an extra database call to collect user's role and check if he even has access to this particular part of application. I could store it in session, but RESTful API is supposed to be stateless.
Thanks for any help as I'm just starting to dig into OAuth and WebAPI authentication. I know that I can customize everything to work as I want (so use session to store user data, etc.), but I wanted to know what the good practices are and which of them are provided out of the box with default WebAPI project in VS2013 and which need to be implemented manually.
(1) the latter is correct. The server verify token by machine key and can decipher and validate its contents.
(2) You got that correct. Its best to keep the token size min. tbh I am looking to see what others are doing about this. (+1 for the question.)