OAuth implementation including login using internal database - authentication

I want to include the oauth2 authentication flow into my application, but also provide an internal database (regular register / login) as an authentication method.
I'm not that sure how to approach that behavior, as I would love to have one single state for the authentication. I've thought about exposing the authentication using the internal database as an OAuth2 application itself, therefor token management etc can be generalized.
This would be a basic example of my thought process:
To distinguish between the multiple OAuth providers, I'd have wrapped the actual token inside a JWT, which also contains the providers name (as well as have a spam protection in my backend, instead of spamming the actual provider).
I'm not sure if it's that good to store the actual user data in a database as well - But I'd need some kind of overview of registered users for the administrators to see - and maybe block or delete.
My questions in particular:
Should the OAuth token be wrapped in a JWT for identification of the provider?
Is it bad practice to store the user data in a database as well? (If not, how much data should be stored [username, ...] and when should the data be refreshed?)
Is there anything else I should keep in mind when doing the authentication flow as it is?

Related

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.

Is JWT right for me?

I've done a fair amount of research on the many different ways to authenticate and authorize users who use my frontend application to access my REST API. I've built a system that uses OAuth2 and JWT and need a sanity check since I'm working on this alone.
For a bit of background, my frontend is built using Vue.js and my API is built using Django with Django Rest Framework. My team is already planning on concurrently developing the mobile and desktop versions of this app which both would require authentication and authorization as well.
To keep things brief, I'll omit the alternative solutions I have and just talk about the most controversial one.
Right now, OAuth2 (my authorization server) grants users a JWT token using ROPC when they provide their email and password to my frontend client. I should note that my API (my resource server) and authorization server live on the same machine.
My application allows users to essentially signup using different plans (for example a free plan and a paid plan). When a user signs up for a free plan, I need the frontend application to not only disable certain features and elements in the UI, but also I need the authorization server and or resource server to limit what that user is allowed to query based on their plan.
The idea is when a user signs up or logs in, my authorization server will get the associated user record from the database and create a valid JWT with a claim attached that states the user's plan and maybe some other non-personal information. Then once signed it sends it off to the user where the frontend can enable/disable parts of the UI... etc. Hence, if a user logs in on mobile, we can customize the UI based on the same claim sent by the JWT.
My issue is that I don't know if this is a good way to go about it. It seems that everyone I've asked in my circle is split on using JWT or not. Those apposed mostly raise security issues, but, when from what I understand, many of the JWT security pitfalls are well documented and can be avoided just using some commonsense as with any other session/token-based authentication. I'm starting to get analysis paralysis. Please help.
CLASSIFICATION
I would say this is really an API Authorization question, as opposed to an OAuth question:
The role of the Authorization Server and tokens is really just to prove the user's identity
Product specific logic comes after the user logs in and is generally best handled in your app
MY PREFERENCES
Here is how I would handle it:
Save the plan type to your product data when the user signs up
After login, look up the user from the access token
Then look up the user's plan type from your product data
Produce a Claims / Principal object in your API containing both
Enforce business rules based on the plan type claim
I would aim for a Claims object something like this:
class ApiClaims {
// The user id in the access token
userId: string;
// The email
email: string;
// The plan type
planType: string;
// Other claims from the token
// Other claims from product data, eg user roles
}
RESOURCES
If interested in this approach, these blog posts of mine may be of interest:
User Data Management
API Authorization
JWT?
You need some kind of API credential that is sent in HTTPS messages and is web and mobile friendly, so I would use JWTs. You could follow the same pattern with any API credential though.
It depends on what you are trying to protect of course, but JWT bearer tokens are an industry standard. Since you control both the client and the authorization server, you can implement it however you like.
I would look into changing Resource Owner Password Credentials flow to authorization code flow. It will enable you to use social authentication providers like Google or Facebook to sign in users (while still maintaining plan info in your own service). Chances are that people trust those companies more to keep their credentials safe than your company, and it allows you to benefit from any authentication features (MFA) those companies implement.
Also, if you want the clients to read the contents of the token, you should use OpenID Connect id_tokens, as those are guarenteed to be in JWT format.

IdentityServer4 personal access token (github-like) or API key for third party clients

Our current setup is
IdentityServer4
Angular + ASP.NET Core application
Authentication for the app via implicit flow/oidc.
We want to provide APIs for customers, i.e. third party clients, with restricted access (separate set/subset of claims). These clients are mostly non-interactive scripts that download data.
This means that we cannot use any flow which (occasionally) requires user interaction. Personal access tokens, like in github, or some other generate once, reuse for a long time API key or token would be needed.
The long token lifetime would not be a security issue, because the token should only allow access to a few read-only APIs and only for that customer's data - so the responsibility to handle the token(s) falls onto the customer.
The customer should be able to create and revoke such API-access tokens based on their claims. Some users might only claims to access certain APIs.
It would be good if we could later prevent that the user re-uses the same token for multiple clients because of licensing requirements but that is perhaps an entirely new question
How could I achieve this?
I thought about doing this via a custom grant, similar to a delegation grant: user uses app, which calls the asp.net core API, which performs auth with that custom grant, persists that token somewhere (just a plain table in the database full of customer-api-only tokens? I'm not sure about that) and shows it to the user - which can also retrieve it later from storage.
I'm thinking about doing the "delegate"-authentication via our API so that we don't leak the secrets into the Angular application.
I think that we then should be able to have either long-lived access tokens or at least refresh tokens via that custom grant.
2017-12-12 how I think I could solve it
We want a process where the user generates something in our application (i.e. via our client) and this something can later be used by the user's third party client to access the API - or request an access token and then access the API.
We want this access to be tied to the user. This includes
- Disabled user
- Lockout
- Specific claims (e.g. tenant)
This does not lend itself well to a solution that issues access tokens directly, because the token would remain valid even if the user was disabled or locked out. Which means that we cannot use a custom grant or IdentityServerTools to issue tokens directly.
Therefore we should use the client credentials grant, or something similar to it, as this could yield new, short-lived access tokens.
User actually generates a new client, which is pre-filled with claims from the user (such as the tenant - which is immutable) and has a claim that corresponds with the user. This happens transparently. Password should be user-supplied with the option to change it. We only store the relation between user and issued client-ids, no passwords.
We have to create a custom grant, which works similar to client credentials, but also checks if the corresponding user is active etc. (which I think should be possible by injecting UserManager)
Resulting access token lifetime is short, interaction with our APIs is expected to be short-lived.
Assuming it is safe and easy enough to write such a grant, we should be able to cover everything we need.
Of course, I might have completely overlooked something :)

Should I use data contained in an authentication JWT on the client-side?

A server provides a JWT to the client during authentication. That JWT contains information which is then later used by the server. For example, JWT may contain permissions array with the list of all permissions granted to a specific user.
Is it considered bad practice, if client parses the JWT and uses the permissions information contained within it? Is it better for client to make additional call to server (GET /permissions, for example) and behave according to that response?
This will strongly depend on a lot of small details; I'll try not to forget anything, but in theory it should be fine to do so and if certain conditions are met I would not consider it a bad practice.
OAuth2 states that access tokens should be opaque to clients, but JWT is just a token format (Learn JSON Web Tokens) and it's usage in other circumstances does not imply the same rules as OAuth2.
Also note that getting the information from an additional request has the same end result with the additional overhead of one more call. There would be a slight benefit if permissions are very volatile given you could repeat the calls.
However, the important part is more focused on what you mean by the client and how would the client use that information so I'll elaborate on this.
Assumptions:
the client you mention can be deployed as browser-based application (SPA's), native application or be some server-side component acting as a client.
both the server and client are controlled by the same entity.
the client and server components can be seen as a single application, that is, for an end-user the fact there's client and server components makes no difference; they use them as a whole.
Explanation
In this situation the token issued by the server is just a way for the client to later access protected resources without requiring explicit user authentication again; it's a mechanism to maintain a session between the two components.
Given the same entity controls both the client and server, it's acceptable to treat the received token as a whitebox instead of a blackbox. The client can then interpret the information in the token and take advantage of it to provide a better experience for the end-user. However, this implies that the server will need to continue to validate the token and it's permissions accordingly; any interpretation of the data by the client is purely to provide optional functionality.
Furthermore, for clients deployed to hostile environments like it would be the case for a SPA application the decisions taken by looking into the data must only result in purely aesthetic decisions, as the user could fake the permissions data. For example, you could use it to conditionally hide/disable some user interface just so that the user wouldn't have to click it to find out it wasn't allowed to do so.
A good analogy would be Javascript based input validation in web forms; you should do it for better user experience, but the server will need to do it again because the user can bypass the Javascript validation.

What are the advantages to the OpenID OAuth Extension over OAuth?

Why use the proposed OpenID OAuth Extension over another OAuth-based protocol?
Discovery doesn't seem to be a feature. Although the consumer only needs a claimed identifier to start the authentication process, any authorization will still require that the consumer knows the access token URL, signature methods, and have a shared key/secret with the provider.
One benefit is that there's a specified way to ask for specific authorizations, the openid.oauth.scope argument to the authentication request. And one specific benefit for this is that authentication only - for the benefit of the consumer only, with no verifiable token - is defined for free and can be performed without worrying about keeping track of outstanding tokens or the resources they might require.
Are there examples of alternative ways in use to specify the scopes to be requested, perhaps with something in OpenID discovery? Or could this be handled effectively with some kind of REST navigation before the OAuth process, where one of several request token URLs specific to the desired scopes is discovered by interpreting hypertext starting from a well-known URL?
I am researching a delegated authentication and authorization system with several authorization scopes, where the scopes are relevant for different interactions. In other words, the consumer needs to tell the provider which scopes should be presented to the user for authorization.
The OpenID+OAuth extension really has only one significant advantage over standard OAuth:
If you need to authenticate the user and access the user's private data, and the OpenID Provider happens to also be the OAuth Service Provider (the user authenticates with the same service that holds his private data), then the extension will help the user have just one redirect to the OP+SP instead of two separate ones. For the user, this is a huge usability win -- if he happens to be authenticating with his SP.
The risks of supporting the extension is adequately supporting users whose OP and SP are not the same entity (you don't want to say you'll support the extension and then inadvertently lock out users whose OP is not also their SP).
Keep in mind what you really need to know. If you only want to access the user's private data, but don't really care who the user is that you're interacting with, use just OAuth. No reason for the user to give up his identity via OpenID if you're only downloading his photos to offer a photo printing service, for example, or if you already have a non-OpenID account for this user.