How to navigate to a specific page in Angular after OpenID Authentication
Imagine you are building an application that requires user to login to view certain sections.
The application uses OpenId protocol for login, where the user is redirected to the identity provider login page and after authentication the user is redirected back to the website.
Lets say the requirement is such that user needs to be redirected for login only when user has navigated to a certain route "/me/:id", and post login the user needs to be redirected to the exact route from where the login was first initiated.
Its a usual practice that we redirect user to the root "/" after login, but how do we persist and navigate to the same route after login?
Another problem here is that since the application navigates to a different domain (of the identity provider), any persisting logic or storage won't correctly work.
So how do we let the application know from which route the login was initiated after it navigates back from an identity provider in OpenId?
We ran into a similar situation once, and the answer was in the query parameters that we pass while building the OpenId login url.
OpenId specification has a query parameter called "state" which gives us provision to preserve the previous state of any data of the application (like the route in our case). We will pass any data in this query parameter to the identity provider and it will be returned back in the url when the identity provider redirects to our application.
The URL for a typical Identity Provider login query will be as below -
GET /authorize?
response_type=code
&scope=openid email
&client_id=12345
&state=af0ifjsldkj
&redirect_uri=https://app.example.com/
The response url returned by the Identity Provider will be as below -
HTTP/1.1 302 Found
Location: https://app.example.com/?
code=SplxlOBeZQQYbYS6WxSbIA
&state=af0ifjsldkj
In the above example, the Identity provider redirects to the url provided in the redirect_uri parameter of the request, which should also be registered under valid urls on the provider side.
The identity provider also returns the state parameter in the response url, which is same as the one passed in the request parameter.
We can use this parameter to persist any data (like the route). This is particularly helpful when we are developing such a functionality in a client-side SPA framework such as Angular.
Keep in mind that since we are passing data out of our own domain, it is highly recommended to pass non-sensitive data such as route paths etc. and encode the data since we have to pass it in the URL.
That is how I approached this scenario with OpenId. Do you think we can approach this in a different way? Let me know!
Follow me on Medium - https://isriramkumarm.medium.com/
Subscribe to my Newsletter and get notified whenever a new post drops - https://codingramen.substack.com/