A-Sharabiani
A-Sharabiani

Reputation: 19377

How to redirect to the return URL in token based authentication

Description

In my mobile application, the user tries to access a resource which requires authentication.

After logging in and obtaining the access token, I want to redirect them to the originally requested page (the return Url).

Question

In a token-based authentication, how to redirect to the return url?

Example

Consider this scenario:

1 - I have a menu in my mobile application "My Profile" which opens a WebView and navigates to mycoolwebsite.com/myprofile.

2 - The server (MVC controller) redirects to a Login Page with the returnUrl as in the URL. mycoolwebsite.com/login?returnUrl='/myprofile' because user cannot access mycoolwebsite.com/profile without logging in.

3 - User sees a Login Page, they enter their username and password, and press the Login button.

4 - A POST request will be send to the _Token Endpoint _ of the ASP.NET application, including username and password and grant_type of password

5 - The server validates the credentials, and issues a Token. It will send the token back to the client as a JSON object.

Problem: after obtaining the Token, I need to redirect the user back to mycoolwebsite.com/profile which they originally requested.

In an ASP.NET MVC application, this happens automatically with the MVC template.

However in WebAPI, I'm not sure what is the proper way to do this.

Upvotes: 1

Views: 10007

Answers (1)

Jan Deutschl
Jan Deutschl

Reputation: 571

With Cookie Authentication it works like this:

  1. User submits the login form, making a POST request to mycoolwebsite.com/login?returnUrl='/myprofile'
  2. The server authenticates the user and if the authentication is successful it returns 302 Redirect response with Location and Set-Cookie headers. Location header contains default redirect url (usually "/"), or value from returnUrl parameter (in this case "/myprofile").
  3. Finally the browser sets the authentication cookie and then redirects to the new location.

Bearer Token authentication (most likely your case)

  1. The user fills the login form and make an Ajax request to mycoolwebsite.com/token

  2. If the authentication is successful the server replies with 200 OK status code and returns the accessToken.

  3. The client then reads the response body and store the accessToken for further use. Now it's up to you. You can read the returnUrl parameter from URL and redirect user to mycoolwebsite.com/myprofile.

So the difference between these two is that the redirection occurs on server-side (via 302 Redirect response) or on client-side.

Hope it helps.

Upvotes: 4

Related Questions