Remembering Authorization - oauth-2.0

I'm playing around with the new laravel/passport package, thinking about using this as a SSO service, and I have followed the video from the laracast (that link might not work if you do not have an account. If not, it just guides you through getting a sample project up). The site works as expected; I am able to authenticate a user from a client application, and execute calls against the api using the returned API token.
However, even though I have authorized the client to access the protected resources, everytime I log in to the client I have to re-authorize the client. In case what I am saying is not making sense, this is the flow:
Visit my-client.app
Redirect to sso.app\oauth\authorization (Authorization Server) to get authorization_code
Login to sso.app
Authorize my-client.app to access sso.app resources
Redirect to my-client.app with authorization_code
Make POST request to sso.app\oauth\token with authorization_code to get token
Make requests to sso.app protected resources using token
Log Out of my-client.app
Redirect to sso.app/logged-out (Page saying you logged out of my-client.app)
Visit my-client.app
Redirect to sso.app\oauth\authorization to get authorization_code
At this point, the client is already logged into sso.app and has already granted authorization for my-client.app to access sso.app's protected resources. Currently, sso.app is asking me to again grant authorization before it will give me an authorization_code. What I would like is for sso.app to realize that authorization has already been granted for the client by the user, so it should just issue an authorization_code without requesting for authorization again.
As an example, I am using Google to sign into SO, but I am not being asked for authorization every time.
EDIT:
It seems that what I am wanting to do laravel/passport cannot do out of the box.
An idea that I have is to create a table client_user_authorizations that will track what users have authorized what client. I will then add a trigger (I would rather tie into the completeAuthorizationRequest method on the class extending GrantTypeInterface for the Authorization Grant, but that seems like a major pain) to the oauth_auth_codes table that will insert to client_user_authorizations table on insert.
I would then make my own controller in place of passport's AuthorizationController (handles GET:/oauth/authorization) that will call a method to see if the resource owner has already authorized the client and call the necessary methods to issue the authorization_code if that is the case. Otherwise, the current flow will occur.
What issues can you see with what I am thinking of doing?

Related

Doorkeeper OAuth application table is necessary for authorization?

I'm trying to add the Doorkeeper plus devise with google and facebook user authorization on API!
I followed this post https://www.vic-l.com/jwt-with-refresh-token-using-devise-and-doorkeeper-without-authorization
And this:
https://naturaily.com/blog/api-authentication-devise-doorkeeper-setup
To start with, both remove the oauth_applications table.
I've done as the tutorials but I'm getting this response:
response_code: "doorkeeper.errors.messages.unsupported_grant_type",…}
response_code: "doorkeeper.errors.messages.unsupported_grant_type"
response_message: "The authorization grant type is not supported by the authorization server."
state: nul
So I would like to know if is necessary the oauth_applications table and set the clients to authorize.
Articles you've mentioned uses Resource Owner Password Flow, i.e they are authenticating the user via credentials to give an access to a resources with an access token. See the configuration option:
grant_flows %w[password]
In such case yeah, you don't need applications (clients which will interact with the API). But if you want to show an authorization window for your customers you should use Authorization Code Flow (from your response I see you're trying to invoke exactly this flow).

Understanding the flow of OAuth2

I'm new to OAuth2 and I'm trying to understand the whole flow of things. For context, I'm thinking of making a web dashboard where users log in via Discord's OAuth2 API.
This is how I think the flow works based on my understanding so far:
User goes to my site and clicks a login link
My site redirects them to Discord with my client ID and a redirect URL #1 in the query string
Discord redirects them back to my site at redirect URL #1 with an authorisation code in the query string
My site takes this authorisation code and along with my client ID, client secret and redirect URL #2, uses all these to fetch an access token and refresh token from Discord
If I do get an access token, that means the user is now "logged in" (authorisation code worked)
My site finally redirects the user to a page and is now free to send requests to Discord's API with the access token, while saving the access token and refresh token. Just for example, say the page states their Discord username
I'm learning from this guide, and what confuses me is this code snippet from the guide. At line 5, it provides the redirect URL #2 mentioned above, in the query string. I'm not sure what it's for.
Also, I'm not very sure how to continue once I have the access token. If multiple users log in, I'd have multiple access tokens on hand. Say a user wants to access the page again, how do I uniquely identify them and know which access token to use to send requests to Discord's API? (for this example, the request would give me their username which I'd display on the page)
Yeah, I probably got a lot of concepts wrong. Any clarification would be greatly appreciated!
Edit: I've done more research into this, and found a much better guide here.
For my question about the second redirect URL, the examples in the official documentation specify a redirect_uri when doing both an access token and a refresh token exchange. However, this new guide makes do without for their access token exchange. Perhaps they missed it out? As this other stack overflow question says:
As an added measure of security, the server should verify that the redirect URL in this request matches exactly the redirect URL that was included in the initial authorization request for this authorization code. If the redirect URL does not match, the server rejects the request with an error.
I suppose this means that after the first access token exchange, any refresh token exchanges or straight up API requests with access tokens need to match the original redirect_uri of said first access token exchange. So I should use one and only one redirect_uri, and the refresh token exchanges/API requests do not actually use the redirect_uri, rather it's used for further security.
As for the whole login procedure, it seems I have to link the access & refresh tokens I obtain to a user session, and for that I'll look into using this passport strategy, passport-discord. Then, once the session expires, I'll discard the two tokens, and they'll have to click login again, but I can make use of this prompt option:
prompt controls how the authorization flow handles existing authorizations. If a user has previously authorized your application with the requested scopes and prompt is set to consent, it will request them to reapprove their authorisation. If set to none, it will skip the authorization screen and redirect them back to your redirect URI without requesting their authorization.
From there I think I'd just store the new access and refresh tokens associated with that user.
I'd really appreciate if any mistakes in my thought process could be pointed out!
Your summary seems good to me Mr Cloud - worth clarifying whether you are developing an SPA or (old) web app with a server side. Most commonly the first is cookieless, whereas the second stores a refresh token in a cookie. A key thing is to understand what the OAuth message workflow looks like. For SPAs and APIs this write up of mine may help you clarify what you want: https://authguidance.com/2017/09/26/basicspa-oauthworkflow/
Happy to answer any follow on questions ..
You can use the implicit grant to use with SPA
https://discord.com/developers/docs/topics/oauth2#implicit-grant

How to implement OpenID Connect authentication with 3rd party IDPs in a microservices architecture

For the past 10+ days I've read an watched ALL the content I could find on understanding OAuth2 and OpenID Connect, only to find that many people disagree on the implementation, which really confuses me.
To my understanding, all the articles and examples I found assume you want access to eg. google calendar, profile info or emails if you eg. login with google, but I do NOT need to access other than my own API's - I only want to use Google, Facebook etc for logging in, and getting an id which I can link to my user in my own database - nothing more than that.
I'll try illustrate my use case and use that as an example.
A note on the diagram: the Authentication service could probably be built into the API Gateway - not that i matters for this example, since this is not about "where to do it", but "how to do it the best way" possible, for an architecture such as mine, where it's used for my own API's / Microservices, and not accessing Google, Facebook etc. external API's
If you can understand what I'm trying to illustrate with this diagram above, please tell me if I've misunderstood this.
The most basic requirements for this architecture you see here are:
Users can login with Google, Facebook, etc.
The same login will be used for all micro-services
OpenId user will have a linked account in the database
User access is defined in my own db, based on groups, roles and permissions
I do not intend to use external API's after the user is authenticated and logged in. No need for ever accessing a users calendar, email etc. so I really just need the authentication part and nothing else (proof of successful login). All user access is defined in my own database.
So a few fundamental questions comes to mind.
First of all, is OpenID Connect even the right tool for the job for authentication only (I'll have no use for authorization, since I will not need read/write access to google / facebook API's other than getting the ID from authenticating)?
People generally do not agree on whether to use the ID or Access token for accessing your own API's. As far as I understand the ID token is for the client (user-agent) only, and the access token is for eg. accessing google calendar, emails etc.... External API's of the OpenID Provider... but since I'll only be accessing my own API's, do I event need the access token or the ID token - what is the correct way to protect your own API's?
If the ID token is really just for the client, so it can show eg. currently logged in user, without going to the DB, I have 0 use for it, since I'll probably query the user from from the db and store it in redux for my react frontend app.
Dilemma: To store user details, groups, roles and permission inside JWT or not for API authorization?
By only storing the user identifier in the token, it means that I always allow authenticated users that has a valid token, to call endpoints BEFORE authorization and first then determine access based on the db query result and the permissions in my own database.
By storing more data about the user inside the JWT, it means that in some cases, I'd be able to do the authorization / access (group, role, permission) check before hitting the API - only possible with user info, groups, roles and permission stored inside a JWT issued upon login. In some cases it would not be possible due to eg. the CMS content access permissions being on a per-node level. But still it would mean a little better performance.
As you can see on the diagram I'm sending all API requests through the gateway, which will (in itself or with an authentication service) translate the opaque access token into some JWT with an identifier, so I can identify the user in the graph database - and then verify if the user has the required groups, roles and permissions - not from an external API, but from my own database like you see on the diagram.
This seems like a lot of work on every request, even if the services can share the JWT in case multiple services should need to cross call each other.
The advantage of always looking up the user, and his permissions in the db, is naturally that the moment the user access levels change, he is denied/granted access immediately and it will always be in sync. If I store the user details, groups, roles and permission inside a JWT and persist that in the client localstorage, I guess it could pose a security issue right, and it would be pretty hard to update the user info, groups, roles and permissions inside that JWT?
One big advantage of storing user access levels and info inside the JWT is of course that in many cases I'd be able to block the user from calling certain API's, instead of having to determine access after a db lookup.
So the whole token translation thing means increased security at the cost of performance, but is is generally recommended and worth it? Or is it safe enough to store user info and groups, roles, permissions inside the JWT?
If yes, do I store all that information from my own DB in the ID Token, Access token or a 3rd token - what token is sent to the API and determines if the user should be granted access to a given resource based on his permissions in the db? Do I really need an access token if I don't need to interact with the ID providers API? Or do I store and append all my groups, roles, permissions inside the ID token (that doesn't seem clean to me) issued by OpenID connect, and call the API and authorize my own API endpoints using that, even if some say you should never use the ID token to access an API? Or do I create a new JWT to store all the info fetched from my database, which is to be used for deciding if the user can access a given resource / API endpoint?
Please do not just link to general specs or general info, since I've already read it all - I just failed to understand how to apply all that info to my actual use case (the diagram above). Try to please be as concrete as possible.
Made another attempt to try and simply the flow:
The following answer does only apply for a OpenID Connect authentication flow with a 3rd party IDP (like Google). It does not apply for an architecture where you host your own IDP.
(There are some API gateways (e.g Tyk or Kong) which support OpenID Connect out of the box.)
You can use JWTs (ID token) to secure your APIs. However, this has one disadvantage. JWTs cannot be revoked easily.
I would not recommend this. Instead you should implement an OAuth2 authorization server which issues access tokens for your API. (In this case, you have two OAuth2 flows. One for authentication and one for authorization. The ID and access token from the IDP are used only for authentication.)
The following picture shows a setup where the API gateway and authentication/authorization server are two separate services. (As mentioned above, the authentication/authorization can also be done by the API gateway.)
The authentication flow (Authorization Code Grant) calls are marked blue. The authorization flow (Implicit Grant) calls are marked green.
1: Your web app is loaded from the app server.
2a: The user clicks on your login button, your web app builds the authorization URL and opens it. (See: Authorization Request)
2b: Because the user hasn't authenticated and has no valid session with your authorization server, the URL he wanted to access is stored and your authorization server responds with a redirect to its login page.
3: The login page is loaded from your authorization server.
4a: The user clicks on "Login with ...".
4b: Your authorization server builds the IDP authorization URL and responds with a redirect to it. (See: Authentication Request)
5a: The IDP authorization URL is opend.
5b: Because the user hasn't authenticated and has no valid session with the IDP, the URL he wanted to access is stored and the IDP responds with a redirect to its login page.
6: The login page is loaded from the IDP.
7a: The user fills in his credentials and clicks on the login button.
7b: The IDP checks the credentials, creates a new session and responds with a redirect to the stored URL.
8a: The IDP authorization URL is opend again.
(The approval steps are ignored here for simplicity.)
8b: The IDP creates an authorization and responds with a redirect to the callback URL of your authorization server. (See: Authentication Response)
9a: The callback URL is opened.
9b: Your authorization server extracts the authorization code from the callback URL.
10a: Your authorization server calls the IDP's token endpoint, gets an ID and access token and validates the data in the ID token. (See: Token Request)
(10b: Your authorization server calls the IDP's user info endpoint if some needed claims aren't available in the ID token.)
11a/b: Your authorization server queries/creates the user in your service/DB, creates a new session and responds with a redirect to the stored URL.
12a: The authorization URL is opend again.
(The approval steps are ignored here for simplicity.)
12b/+13a/b: Your authorization server creates/gets the authorization (creates access token) and responds with a redirect to the callback URL of your web app. (See: Access Token Response)
14a: The callback URL is opened.
14b: Your web app extracts the access token from the callback URL.
15: Your web app makes an API call.
16/17/18: The API gateway checks the access token, exchanges the access token with an JWT (which contains user infos, ...) and forwards the call.
A setup where the authorization server calls the API gateway is also possible. In this case, after the authorization is done, the authorization server passes the access token and JWT to the API gateway. Here, however, everytime the user infos change the authorization server has to "inform" the API gateway.
This is a very long question. But I believe most can be summarised by answering below,
To my understanding, all the articles and examples I found assume you want access to eg. google calendar, profile info or emails if you eg. login with google,
You do not necessarily use Access token (ID token in some occasions) to access the services offered by token issuer.You can consume tokens by your own APIs. What these Identity Providers (synonym to Authorization server, or IDP in shorthand) is to hold identities of end users. For example, typical internet have a Facebook account. With OAuth and OpenID Connect, the same user get the ability to consume your API or any OAuth/OIDC accepted service. This reduce user profile creation for end users.
In corporate domain, OAuth and OIDC serves the same purpose. Having a single Azure AD account lets you to consume MS Word as well as Azure AD's OIDC will issue tokens which can be used to Authorise against an in-house API or an third party ERP product (used in organization) which support OIDC based authentication. Hope it's clear now
A note on the diagram is that the Authentication service could probably be built into the API Gateway - not sure if that would be better?
If you are planning to implement an API gateway, think twice. If things are small scale and if you think you can maintain it, then go ahead. But consider about API managers which could provide most of your required functionalities. I welcome you to read this article about WSO2 API manger and understand its capabilities (No I'm not working for them).
For example, that API manager has built in authentication handling mechanism for OAuth and OIDC. It can handle API authentication with simple set of configurations. With such solution you get rid of the requirement of implement everything.
What if you can't use an API manager and has to do it yourself
OpenID Connect is for authentication. Your application can validate the id token and authenticate end user. To access APIs through API Gateway, I think you should utilise Access token.
To validate the access token, you can use introspection endpoint of the identity provider. And to get user information, you can use user-info endpoint.
Once access token is validated, API gateway could create a session for a limited time (ideally to be less or equal to access token lifetime). Consequent requests should come with this session to accept by API gateway. Alternatively, you can still use validated access token. Since you validated it at the first call, you may cache for a certain time period thus avoiding round trips to validations.
To validate user details, permission and other grants, well you must wither bind user to a session or else associate user to access token from API gateway at token validation. I'm also not super clear about this as I have no idea on how your DB logic works.
First Appreciate your patience in writing a very valuable question in this forum
we too have same situation and problem
I want to go through ,as images are blocked in our company in detail
Was trying to draw paralles to similar one quoted in the book
Advance API In Practise - Prabath Siriwerdena [ page 269]Federating access to API's Chapter. Definitely worth reading of his works
API GW should invoke Token Exchange OAUTH2.0 Profile to IDP [ provided the IDP should support TOken Exchange profile for OAUTH 2.0
The Absence of API Gateway , will result in quite bespoke development
for Access Control for each API Check
you land up in having this check at each of the api or microservice [ either as library which does work for you as a reusable code]
definitely will become a choking point.]

Difference between Access Grant and Access Token

I can't figure out the difference between Token and Grant in Doorkeeper. In which moment, Doorkeeper creates an Access Grant and when an Access Token? The documentation doesn't seems to say nothing about it and now I'm reading the code but is not a dozen lines.
I recommend to also read the documentation of oauth2
As I understand, Doorkeeper is based on the protocol described in that documentation too.
In doorkeeper, you will get access grant first and then access token.
Access grant usually only lives very short (the default in doorkeeper is 10 minutes).
You will get this by requesting GET to api-url/oauth/authorize (don't forget to put client_id, redirect_uri, and response_type as parameter. response_type will have value "code").
Once user allow the apps (user clicks "allow" button), doorkeeper will return the access grant as parameter in the returning url.
Get that code and you can now use it to make POST request to api-url/oauth/token to get your access_token and refresh_token.
Using access_token, you can get the resources of the API in a limited time (Doorkeeper's default is one hour if I'm not mistaken).
When acces_tooken expired, use refresh_token to get new access_token and so on.
In summary, access grant is the key that given as the sign that user has allowed the apps to use its resources.
Access token is the key that is given to permit an apps to use resources in a limited time which has defined.
Hope it can help.
I'm assuming you're talking about the Web Server flow, as you're using a Ruby gem in a Rails app (as you know, there are 4 flows).
Usually in the Web Server flow, Grant is the moment when the user clicks in a link to consent authorization: he/she will be asked to authorize the app to read/write data.
If consent is granted, then the app will get a temp code. With this code, in the background, the app will ask the Token for the service provider.
Then, only with the Token, the app will be able to use the service provider APIs.

Web API [Authorize] Attribute Without User Logging In Or Requesting Token With Password?

Correct me if I'm not understanding something. I'm working with a fresh Web API application generated from a VS template.
The user does register right on the login page of the Web API app.
It appears that a user can register from outside the Web API app (from ANY device that knows the api/Accounts URL), but it requires passing sensitive information in plain text.
The sample ValuesController has the [Authorize].
Accessing /api/Values from the browser will throw a 401 if the user is not logged in.
Accessing /api/Values from Fiddler will also throw a 401 even if the user is logged in. This is because it requires an Authorize: Bearer header, which the access token isn't available from outside the web application.
There is a token endpoint that we can use to request a token from outside the app, but using the built-in token endpoint requires the user's username and password as plain text to be sent.
I guess all the work needs to be done from an external trusted client application (which must have access to the same database that stores user info). From the client application, how would I create an access token so that I can make a request that would have that access token in the header?
Suppose that I was able to achieve generating an acceptable access token from the client. Will the [Authorize] attribute still block access because the user would technically not be logged in? Or does [Authorize] actually log the user in if it doesn't result in a 401?
The AuthorizeAttribute will block access when the IsAuthenticated property of the current IIdentity is false. This is entirely separated from the access token.
Your steps are all right. But i think you are mixing you understanding of the last part with cookies authentication and token authentication.
Will the [Authorize] attribute still block access because the user
would technically not be logged in? Or does [Authorize] actually log
the user in if it doesn't result in a 401?
With cookie authentication this would be a problem that the user would technically need to be logged in and a valid session would need to exist on the server.
However this would not be the case on with token authentication. As long as you have a valid bearer token, you may access the api from any device.

Resources