Understanding the flow of OAuth2 - oauth-2.0

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

Related

Authorization and Authentication in microservices - the good way

I'm considering a microservice architecture and I'm struggle with authorization and authentication. I found a lot of resources about oauth2 and openid connect that claim they solve the issue but it is not clear enough for me.
Let's consider we have a following architecture:
In my system I want to add a feature only for a certain group of users defined by role. I want to also know the name of the user, their email and id.
After my research I find the following solution to be a good start:
SPA application displays login form.
User fills in the form and sends POST request to authN&authZ server.
The server replies with access token (being a JWT) that contains name, email, id and role of the user. The response contains a refresh token as well.
SPA application stores the token and attaches it to every request it makes.
Microservice 1 and Microservice 2 check if the token is valid. If so, they check if the role is correct. If so, they take user info and process the request.
How far away from the good solution I am? The login flow looks like Implicit flow with form post described here but with implicit consents and I'm not sure if it's fine.
Moving forward, I find passing user data in JWT (such as name, email) to be not a good solution as it exposes sensitive data. I found resources that say it is recommended to expose only a reference to a user in token (such as ID) and replace such token with a classic access_token in reverser-proxy/api gateway when sending a request to a microservice. Considering such solution I think that following scenario is a good start:
SPA application displays login form.
User fills in the form and sends POST request to authN&authZ server.
The server replies with access token and refresh token. API gateway (in middle) replaces access token with ID token and stores claims from access token within its cache.
SPA application stores the token and attaches it to every request it makes.
Handling a request, API Gateway takes ID Token and based on the user ID generates a new access token. The access token is send to microservice 1 or microservice 2 that validate it as previous.
How do you find such solutions? Is this a secure approach? What should I improve proposed flow?
Thanks in advance!
You are on the right tracks:
ZERO TRUST
This is an emerging trend, where each microservice validates a JWT using a library - see this article. JWT validation is fast and designed to scale.
CONFIDENTIAL TOKENS FOR CLIENTS
Internet clients should not be able to read claims that APIs use. The swapping tokens in a gateway concept is correct, but the usual approach is to issue opaque access tokens here, rather than using ID tokens. At Curity we call this the Phantom Token Approach.
SECURE COOKIES IN THE BROWSER
One area to be careful about is using tokens in the browser. These days SameSite=strict HTTP Only cookies are preferred. This requires a more complex flow though. See the SPA Best Practices for some recommendations on security.
SPAs should use the code flow by the way - aim to avoid the implicit flow, since it can leak tokens in the browser history or web server logs.
SUMMARY
All of the above are general security design patterns to aim for, regardless of your Authorization Server, though of course it is common to get there one step at a time.
Don't use your own login form. As Garry Archer wrote, use the auth code flow with PKCE which is the recomended flow for applications running in a browser.
If you don't want to get an ID token, don't ask for the openid scope in the initial auth request. The type of issued access tokens (JWT or opaque) can often be configured on your OAuth2 server. So I see no need to issue new tokens at your gateway. Having more token issuers opens more ways of attacking your system.
Your backend modules can use the userinfo endpoint, which will give them info about the user and validate the token. This way, if the token was invalidated (e.g. user logged out), the request processing will not proceed. If you validate just a JWT signature, you will not know about the token being invalidated.
If you plan to make requests between your backend modules as part of of a user request processing, you can use the original access token received from your SPA as long as your modules are in a safe environment (e.g. one Kubernates).

Understanding oAuth implicit flow

I'm working with the New Twitch API and I wish to get data from and end point using javascript.
Endpoint https://dev.twitch.tv/docs/api/reference/#get-streams
For the means of testing, I'm hitting the endpoint with Postman and it's working.
According to the docs, I need to provide a client-id which I can get from my developer dashboard and I add this as a header in Postman.
What I'm confused about is that it seems for as long as you have someones client-id (which is going to be exposed when using JS) anyone can hit this endpoint? What stops someone taking my client-id or me taking someone elses and using it for their/my own purposes and what are the risks with that?
In general, it's the Redirection URL that's the lynchpin.
The flow works like this:
You register your app at Twitch. As part of this step, you specify your redirection URL (https://dev.twitch.tv/docs/authentication/#registration)
A user visits a web page that makes use of the API
The user needs to authenticate. The web page hands off to the Twitch OAUTH authentication page, passing along its Client ID
The user authenticates with Twitch
Twitch redirects the user to the Redirection URL set up in step #1, along with a Bearer Token.
As you can see in step 5, the token is only sent back to your Redirection URL. If another website tried to get a user authenticated using your Client ID they would never receive back the token.
The area I think you could run into trouble is rate limiting. Twitch limits you to 30 queries per minute with a Client ID and no Bearer Token or 120 queries per minute with both. If a malicious user is using your Client ID then it would eat up your rate limit. https://dev.twitch.tv/docs/api/guide/

How do OAuth 2.0 refresh tokens work?

I've been reading abount using Passport for the authentication process in a MEAN stack web app. I've been following this tutorial, but I got confused when it comes to the refresh tokens.
I do understand that those tokens are used to get a new access token for the user once it has expired, as explained here and in any other OAuth tutorial about thos tokens, but what I don't understand is how the server knows which refresh token must be used if the user hasn't provide any credential (it is supposed to provide the credentials just the first time is logging in).
Can anyone help me with this to fully understand how this works?
Thanks a lot :)
The Authorization Server issues the first refresh token after the user has authenticated. It then stores the association between refresh token and user as part of server side state so that it knows which refresh token was issued, whether it is still valid and for which user.
When the Client comes back to the Authorization Server with the refresh token later, the server can lookup the context and associated user from the server side storage.
Well, finally it turned out that the tutorial I was following was wrong (at least on what it comes to the refresh tokens).
On the tutorial it said that Passport use the refresh tokens to send a request to the Auth Server to get a new access tokens. Well, that's not true. According to Jared Hanson, the author of Passport, Passport doesn't handle refresh tokens, that's something the backend of the applications have to handle if desired. Passport is just meant to make the first request to the Auth Server, when you get the access and refresh tokens. Then you can use refresh tokens to request new access tokens, for example using background tasks to check if any access token is going to expire anytime soon.
I think the one who wrote that tutorial was confused cause the second time you login with whatever strategy is available (Facebook, for example), the service doesn't ask for credentials, but that's not because of the refresh tokens, that's just cause the browser is saving the FB session. If you go to FB and logout, the next time you try to login in the app with FB, it will ask again for the credentials. In fact, if I'm not wrong, access and refresh tokens should be removed once a user logs out. Kind of surprising that you could find that kind of mistakes in a IBM developers blog.
BTW, Jared Hanson's comment about how Passport works (without using refresh tokens) can be found here. Since is an old issue, I asked him myself on Twitter and the answer was just the same :)

Dealing with expired access tokens in OAuth2 implicit grant

The specification of OAuth2 states that an authorization server must not issue a refresh token when using implicit grant. In our use case we protect a RESTful API with OAuth2 and use a Single Page Javascript application as a client for this API. As it would be very difficult to redirect to the authorization server after an access token has expired, we are searching for a better way to get a new valid token. I could think about two different approaches and wonder which one could be better:
Use a hidden iframe to Rerequest a valid access token. For this it is necessary to include a parameter like “prompt=none” which tells the OAuth provider neither to challenge authentication, nor to display an authorization page. If the user is authenticated and has authorized the application the server will send back an access token in the urls # parameters. If one of the previous conditions is not fulfilled, it will redirect with an error like #error=authentication%20lost. With this behaviour we can use short lived access tokens also with an implicit flow.
We could use an additional scope (e.g. offline) which tells the server to hand out a refresh token. Even if the original spec says that implicit flow does not issue refresh tokens (which is correct if the client only uses OAuth it for a first authorization) you are free to define your own scopes for your particular application. You should consider to only allow this scope from well-known clients.
Both approaches are very similar to those of OpenID Connect. Unfortunately there are not many implementations of OpenID Connect at the moment. So first step would be to extend the OAuth2 server until OIC will be more popular.
So which approach should be preferred?
EDIT: The token endpoint needs client authentication, which is only possible for confidential clients like server-side applications. With the second approach it would only be possible to let the RESTful API in our case the resource provider to refresh the token and send it back to the client. I think this would be a security risk. So probably we have only one valid approach.
I'm trying to achieve the exact same thing at the moment.
I've actually implemented hidden iframe approach and then realized you have to be very careful with iframes. Any malicious website can contain your iframe and get access token easily if you don't specify X-Frame-Options.
Best approach for refreshing token should be password grant as specified by the spec. (I wanted my users to login with their facebook account & implicit flow was easier to develop this. I have not quite figured out how to do this with password grant.)
2nd approach also came accross my mind and seems much safer than the 1st to me, since you can usually trust the https & browser storage to keep your tokens secret.
Edit
I realized, even with X-Frame-Options most browsers can't prevent redirects, because this header is attached to the response body and redirected URL will be exposed, therefore access tokens exposed.
Update
Looks like hash fragment is protected by the browser when accessed from the parent page within different domain. So I assume #access_token is safe. My bad. Just as a reminder callback page has to store the access token in its own right, instead of (my original intention) delegating it to the parent page like window.parent.storeAccessToken(hash); which obviously is a dumb thing to do.
From the OAuth0 website:
If you need to authenticate your users without a login page (for example, when the user is already logged in via SSO scenario) or get a new access_token (thus simulate refreshing an expired token), you can use Silent Authentication.
As for the Silent Authentication:
However, redirecting users away from your application is usually considered disruptive and should be avoided, from a UX perspective. Silent authentication lets you perform an authentication flow where Auth0 will only reply with redirects, and never with a login page.
This will allow you to log back the user using an SSO token, without having to prompt him for credentials again.

Oauth flow for google

I am trying to impliment Oauth for my webapplication for google.I am worked upon a POC and it working fine but i have a confusion and not sure how best it can be achieved.
I am using scribe java API for Oauth.
here are the steps i am performing.
Getting request token from Google.
Redirecting user to Google to authenticate them self and authorize my serivice to access his/her few details.
get Access Toekn from google by providing request token and verification code given by google.
Accessing user info once google provide Access token.
now my main confusion is at step no 3, since i am working on a web-application so it will be a 2 step process.
Redirecting user to google
Handling back google redirect.
In order to get an Access token i need to provide same request token which i got at step1 else my request being rejected by the user.
The request token contains 2 things
Toekn -->which is based on the registered application so not an issue
Secret-->This is always being a random string so it should be same when asking for access token
that means i need to store this secret either in my session or some where so that i can access this secret when user is being redirected back to my application.
My confusion is,since in order to save it in session i have to create a unique key and some way to access it in the other action class which will handle Google Redirect back how can i achieve this since at a given time so many user can ask to login using google.
any help in this regard will be much appriciated.
Thanks in advance
When you receive the request token + token secret, use the request token as the unique key of your session to store the token information. After the authorization process, in the callback url, you have access to the request token (it's one of the parameters passed to the callback url). Using this parameter as the session key, you can restore the token information from session, including the token secret, and use it to sign your request for changing the request token for access token. After receiving the access token, a new token secret is returned to you and you can delete the old one from session.
how can i achieve this since at a given time so many user can ask to
login using google
This is not of any problem because for every single user on your site, you are given a different request token.

Resources