Facebook app login with a subdomain - oauth

Since the "Use Strict Mode for Redirect URIs" became obligatory I have an issue with my application. It uses the
user.myapp.com
schema to allow different users to log inte their "work area". But while the list of the users is dynamic, I cannot modify the Client OAuth Settings every time a new user is added.
Is there any solution to this problem?
What I did was to create a dedicated app.myapp.com subdomain, added it to "Valid OAuth Redirect URIs" list and passed it URL to FB login.
But in this case I am getting
Cross-site request forgery validation failed. Required param "state" missing from persistent data.
message (I call FB login from app1.myapp.com, the callback is at app.myapp.com with an intention to redirect back to app1.myapp.com)
Just to clarify: if, for test purposes, I redirect back to app1.myapp.com, everything works great. So the code is correct.

Related

How to validate OAuth state on redirect

I think I am misunderstanding the OAuth OpenID Connect specification and here's why:
I try to implement "Sign in with Apple". You can opt to use a popup or a redirect to an apple page I want to keep it simple at first, so I am using the redirect options. Clicking the "Sign in with Apple" button will redirect me to the apple sign in page having the state filled to prevent CSRF attacks.
After successful authentication, apple "redirects" to my specified redirect url by making a POST request to that URL with the state, code and id_token value.
Now here's the thing: How am I supposed to validate the state, when the POST request originated from a different session? I send a CSRF-Token as the state from the user who clicked on the "Sign in with Apple" button but the response from apple was made as a different session – having a different CSRF-Token.
Am I even supposed to validate the state in this kind of flow? I feel that I have to otherwise someone could just use CSRF to send a POST request to my redirect URL with an arbitrary code and id_token.
Anyone knows how to validate the state? I'd appreciate the help :D Thanks in advance.
Addition: With the popup option everything should work, I receive state, code and id_token in a browser event after successful authentication so I can validate that the state and the nonce both match.
Anyone knows how to validate the state?
It's client responsibility to validate the state to prevent against the CSRF attack. So, client must generate some state value, store it in the available storages (cookies, session, or localstorage) on its side. Pass it to the auth server. Post auth, control is redirected back from auth server to client. Now, client can retrieve the state parameter and compare it with one stored earlier. If values don't match, terminate the flow.

Rails Devise Token Auth Reset Password Flow - How to deep link from 302 redirect

I am trying to implement a reset password flow with devise token auth gem: https://github.com/lynndylanhurley/devise_token_auth
The end client will be a mobile device (e.g. iOS, Android). I am uncertain as to how the native clients will be able to catch the url to reset password and display a password form through deep linking. Here are the general steps as I understand them:
Fire a POST to auth/password with an email and redirect_url
This will send an email with a link to reset the password and an included reset_password_token query param.
Clicking on the link fires a GET to auth/password/edit
This GET then fires a http 302 redirect to the redirect_url sent in the first request with the reset_password_token in the query params. The redirect_url should route to the form intended to display a password field to reset a user's password. On mobile clients, ideally this would be handled as a deep link.
I am confused as to how the mobile apps will handle step 4. I heard it's difficult to deep link in a native app through a 302 redirect/may not be possible. Is there a part of the flow I am misunderstanding perhaps? I'd appreciate any clarity on how I can implement this flow successfully for mobile clients.
For reference here is the guide I am following from the official docs: https://devise-token-auth.gitbook.io/devise-token-auth/usage/reset_password

Session empty after redirect

I've a React JS app, which makes this request to my back-end API. i.e
window.location = "https://my-server.com" + "/gmail/add_account";
cannot set HTTP headers for window.location see this
this server endpoint redirects to Google OAuth page, which returns a response to my redirect_uri.
def add_account
# no auth headers sent here, because front-end has used window.location
gmail_service = GmailService.new
session[:uid] = params["uid"]
redirect_to gmail_service.generate_authorization_url()
end
def oauth_postback
# session object is {} here
# Since there are no authorization headers, I cannot identify my app's user
# How can I identify my app's user here?
end
The problem I'm facing is that when the OAuth flow sends the response to my redirect_uri it does not return include any authorization header, due to which I'm unable to identify which user of my app has launched this OAuth flow.
I've tried setting up a session variable in the /gmail/add_account endpoint, which works fine. After this endpoint redirects to the OAuth screen, and the Oauth flow sends a response to my Oauth redirect_uri, there my session object is {}.
How can I implement this flow such that I know which user has launched this OAuth flow?
You have basically two options:
the state parameter
The state parameter is part of the OAuth2 spec (and is supported by Google). It's a random string of characters that you add to the authorization URL (as a query parameter), and will be included when the user is redirected back to your site (as a query parameter). It's used for CSRF protection, and can also be used to identify a user. Be sure that if you use it, it's a one-time value (e.g. a random value that you store in your db, not the user's ID).
sessions with cookies
If the user has previously logged in, you should be able to identify them by their session cookie. It sounds like this is the approach you're currently taking, but the session is getting reset.
It's difficult to debug this without knowing more about your stack/code, but a good first step would be just trying to load your callback URL without the redirection to Google to see the session object is still empty. If so, that would indicate an issue with how you've implemented sessions generally and not something specific to this flow.
As a note, based on the code you've shared, I'm not sure how params["uid"] is getting set if you're doing a redirect without any query parameters or path parameters.
Finally, you may consider using a managed OAuth service for something like this, like Xkit, where I work. If you have a logged in user, you can use Xkit to connect to the user's Gmail account with one line of code, and retrieve their (always refreshed) access tokens anywhere else in your stack (backend, frontend, cloud functions) with one API call.

Attempting to connect to a IdentityServer4 login page fails

I have an existing website that I want to do a proof of concept with OAuth2 / OIDC. To this end I've configured a locally running IdentityServer4 MVC app as my demo OIDC server following the IdentityServer4 quick setup guidelines. This works fine and navigating to:
http://localhost:5000/.well-known/openid-configuration
Lets me see the discovery document.
I have created a fake login page on this OIDC app which consists of just a login button with no user credentials required.
There's no actual user database and I'm just hard coding some user details to return when the 'authentication' occurs.
In my pre-existing site I've added the OWIN middle wear and am configuring OIDC using the OpenIdConnectAuthenticationOptions. The clientId, scopes, secret etc all match as required and the authority is set to point to my locally running demo OIDC app (http://localhost:5000). The redirect url is set to return to my pre-existing site once authentication is complete.
This all appears to be fine but here's what I want to achieve and can't get working. On my pre-existing site when I navigate to any page that requires authentication I want the user to be redirected to the login page I created on OIDC app. They click the login button (no user details required) and are authenticated and redirected back to the original page.
Currently when I navigate to a protected page I am successfully redirected to the OIDC app but I am redirected to an error page and I don't know why. The error page gives me no detail, it's actually hard coded in the app.
When I look at the discovery document I see that the setting for the 'authorization_endpoint' is set to:
http://localhost:5000/connect/authorize
So I thought maybe I needed to either change that to point to Home/Login which is where I've created the dummy login form, or else I needed to actually create that connect/authorize endpoint and put my form there. Creating the end point makes no difference, it never gets hit and instead I just get the error page on my OIDC app. Changing it to home/login also appears to be ignored.
I am away from my main PC at the moment hence the lack of code snippets but essentially the set up is as per the IdentityServer4 quick setup guide and the OIDC app does appear to be working.
The issue is getting my pre-existing site to properly redirect to the login page.
I've been stuck on this for quite a while now and would like to even get to the stage of seeing the dummy login page. Any pointers are appreciated and again apologies for the lack of sample code.
UPDATE
I've got the login form appearing by setting the openidconfiguration like so:
Configuration = new OpenIdConnectConfiguration()
{
AuthorizationEndPoint = "http://localhost:5000/home/login"
}
However, this isn't logging me in when I click login. On that login action I'm doing this:
await HttpContext.SignInAsync("subjectId","username", authenticationProps);
And then redirecting back to my existing site. However it's not authenticating me and the redirect ends up being redirected back again to the login page.
UPDATE 2
I think the redirect URI should possibly be doing something more. Currently I do the following:
Try and access a restricted page -> Redirected to OIDC server -> Click Login (this sets the subject and user successfully) -> Am redirected to redirect URI which immediately bounces me back to the OIDC server.
So maybe the redirect URI is supposed to confirm login or otherwise do something?
So in the open id connect protocol, the authorize endpoint is used to validate the client information passed as query parameters (client_id, scopes, redirect_uri, etc). In your authentication server, none of that is being checked if all the endpoint does is return a form. Then again the validation can be tedious so keeping the authorize endpoint separate from the endpoint for logging in might be worth a thought.
The developers of Identity Server thought the same thing which is why they set up the endpoint (and endpoint validation) for you as part of the middleware. The validation uses the components that were injected (primarily the client_store, and your defined scopes) to be used by Identity Server.
After the framework validates your authorize request using your client store implementation, it will redirect the user to whichever login page you specify. The login page can be specified by changing it with the a delegate that can be passed in as the second parameter of 'AddIdentityServer' (that takes in something of type IdentityServerOptions that we'll refer to as just 'options'). In the delegate you can specify the login url of the page by changing the value of 'options.UserInteraction.LoginUrl' to the url of the login page.
After the user logs in and you call the signInAsync method on the HttpContext, you're actually supposed to redirect back to a query parameter passed to the login page referred to as the 'return_url' (which is basically the initial authorize endpoint request). This authorize endpoint further validates the cookie and will send the user back to the 'redirect_uri' (if consent on the client is set to false) with a code (if using the authorization code flow) or the id_token and optionally the access token (if using the implicit flow).
Assuming the implicit flow for simplicity, the tokens can be found in the request to the 'redirect_uri' and from there it's all up to you. Commonly the client will issue some kind of cookie (which can potentially contain the id or access token) to mark the successful authentication by the identity provider.

Am I doing this whole API, client app, Oauth/OpenId Connect thing right?

I have some programming experience, but only with PHP and Java enterprise systems. But now I have some ideas about a web app in my new job. Since I am new at this, I would like to share how I have done the whole API in a server, browser app and authentication with Google’s OpenID Connect (I read a lot about Oauth and OpenID Connect, most helpful source was this: https://developers.google.com/identity/protocols/OpenIDConnect).
Server: Laravel - hxxps://coolapp-api.mycompany.com
Client: Angular - hxxps://coolapp.mycompany.com
TL;DR version:
1) User goes to hxxps://coolapp.mycompany.com, gets an Angular app login page. Types in their email, clicks “Sign in with Google”;
2) The app sends the email to hxxps://coolapp-api.mycompany.com/api/sign-in. The server redirects the user to hxxps://accounts.google.com/o/oauth2/auth with all the needed parameters;
3) The user logs in to their Google account, gives my app permission if it’s their first time, and Google redirects them to my server at hxxps://coolapp-api.mycompany.com/sign-in/google/callback. The server checks everything, and if it’s all correct, it creates a JWT token and send a redirect to the client app at hxxps://coolapp.mycompany.com/login/callback?token=JWT-TOKEN
4) The client app gets the token, stores it in local storage, and sends it to the server with every API call
More detailed version:
1) User goes to hxxps://coolapp.mycompany.com, gets an Angular app login page. Types in their email, clicks “Sign in with Google”;
2) The app sends the email to hxxps://coolapp-api.mycompany.com/api/sign-in. The server creates a state token and stores it in cache, associated with the email received. Then the server creates Google’s oauth URL and sends it to the client in the response body. I tried to do it with a HTTP redirect, but Google’s server was responding with an CORS error. The Angular app reads Google’s url from the response and goes there.
3) The user logs in to their Google account, gives my app permission if it’s their first time, and Google redirects them to my server at hxxps://coolapp-api.mycompany.com/sign-in/google/callback?code=AUTHCODE&otherstuff. The server sends the code it received (and all the other needed parameters) to hxxps://accounts.google.com/o/oauth2/token. It receives a id_token with that user’s email and basic info. This app is not public, so I don’t want anyone with a Google Account logging in, only the clients whose emails I added to the server database. So now the server checks if the user’s email in the token is in the database. If it’s not, it sends the user a HTTP 401 - Unauthorized. Then the server checks the state token in it’s cache associated with the email received. If it’s equal to the one received with Google’s redirect, then the server creates another JWT token, but now signed by my server. Finally, it sends a HTTP redirect to hxxps://coolapp.mycompany.com/login/callback?token=JWT-TOKEN with the new token.
4) The client app gets the token, stores it in local storage, and sends it to the server with every API call
Some comments:
Everything is HTTPS;
I added the strictest CSP policies I could to my Laravel server and Angular client;
Currently the app only supports Google’s sign in, while it is in development. Later on I’ll add more.
I made that my server only checks if the user’s email is in the database after they logged in with google because I like that idea that a non-authorized user should have no information about anything. If I made that check before it, during the first round trip, anyone could type an email and discover if that email has an account in my system;
On the last step, when my server sends the JWT token to my client app, I tried sending the token within a cookie, but since my API and my client app have different domains, my client app couldn't read the token. Sending it in the url was the only solution I could find. I tried logging in a popular app that uses Oauth and they did it this way too.
So my question is:
Am I doing something wrong, unsecure, weird?
Thank you all very much
1) Entering an email address every time a user wants to log in is tedious. And it's not needed if the user is already logged in at Google. The user should just click the "Log in with Google" button and get logged in without entering anything. The state parameter can be a random string - not related to the user's email in any way.
2) If you want your backend to process the redirect from Google (using the auth code flow - the backend has the client role in OAuth2 terms), the backend should also initiate a redirect to Google - not by sending data containing the redirect URL. To achieve it, after clicking the "Log in with Google" button, perform a whole page navigation (instead of an XHR request) to /api/sign-in and if the backend returns HTTP 302, the browser will correctly redirect to Google.
3) You should perform request validation (the state parameter) before getting tokens and checking whether the user exist.
On error (access denied), you can consider redirecting the user to an error page with error details instead of returning HTTP 401, since the HTTP code will cause a generic error screen to be displayed to the user. If you want to keep using HTTP codes, I think HTTP 403 Forbidden would be more appropriate.
4) Consider using sessionStorage instead of the localStorage. The sessionStorage gets cleared after closing a browser/tab and it's not shared among tabs. It makes it safer and it allows users to use different identity in different browser tabs.
The tokens your backend issues, is their validity time limited? Is the user required to get a new token after some (short) time period? If not, valid token vales may stay in the localStorage and browser's page history, which can be a security problem.
You can consider using your own OAuth2 auth server (such as RedHat Keycloak) which would accept Google (and later some other providers) for authentication and it would also issue access tokens accepted by your backend.

Resources