I am implementing a Microsoft Authentication in .NET Core that uses azure AD. I managed to implement this authentication correctly and a redirection to a swagger endpoint once the authentication process is completed.
The problem is that the token is given in the redirection URL, as shown below:token in url
And for sending the request to the endpoints, I have to manually copy that token and send it attached to the request, otherwise I will still get an unathorized code.
Is there any way in which upon the redirection I can extract the token and save it in the session (or similar) and that way include it automatically in the next requests that are made?
if not, can I at least extract the token string it in some way? as I didn't find any way to read the actual current value of the url being displayed, only when issuing a request I am able to read the address but thats for the request, not for the actual /swagger/access_token... etc
You had setup everything correctly, the token is given to the client (your web browser) in the URL is a standard pratice. Now it is the responsibility of the client (The web page on your web browser) to send that token to your web server on every request. To handle that you need client-side coding / javascript
You should:
But from the question, I guess that you are not familiar with client - server architecture but just playing with the server part? In such case, one possibility (not recommended) is to:
Change the redirect URL as one of the API/Page you control (http://my-web-server/my-page/Index?access_token=...)
In the server, read the access token from URL and write to cookies
string accessToken = null;
// If the access token is passed as a URL parameter (query string)
if(Request.QueryString["access_token"] != null)
{
accessToken = Request.QueryString["access_token"].ToString();
}
if (!string.IsNullOrEmpty(accessToken))
{
HttpCookie cookie = new HttpCookie("AccessToken", accessToken);
cookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(cookie);
}
Read the token from Cookie instead of Header (In ASP.NET Core read JWT token from Cookie instead of Headers)
Do this only for testing. You should read up on the concept of client vs server and the related concepts (Http request, Http Header, Cookie, Session, Javascript)