Hello my dear developers!
How do you feel today?
Recently I’ve been having at token based authentication in more depth and found a few wringcles in the experience. First, for references please read these 2 articles that do a wanderfull job. They explain how to implement token based authentication in a very simple fashion:
Another more advance resource for managing security is : https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims?view=aspnetcore-6.0
For my simple code reference go to : https://github.com/ambsenyestudi/aspnetcore_3_token_based_authentication
Ok, once you implement token based authentication your typical attempt is to add an authentication header to your httpClient default headers or to the very HttpRequestMessage.
For default header
var response = await client.PostAsync(settings.LoginEndpoint, content).ConfigureAwait(false);
var json = await response.Content.ReadAsStringAsync();
token = JsonSerializer.Deserialize<Token>(json, serializationOptions);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Bearer);
For HttpRequestMessage
var requestMessage = new HttpRequestMessage(HttpMethod.Post, settings.GameEndpoint);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Bearer);
requestMessage.Content = content;
var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
This is all very fine and good, the problem comes if the API that you are calling to has redirect activated.
On your API Startup.cs
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ambseny.ChessEngine.Api v1"));
}
//this causes your redirection when calling to your http url
app.UseHttpsRedirection();
...
}
It took me a tone of research to find this https://github.com/dotnet/runtime/issues/26475
The former basically tells you that on a redirect you loose the authentication headers on you request. So, make sure to direct your calls to the https url or you will never get authenticaiton due to the redirect security fix.
I hope that this was as helpful for me as it was for you.
Happy coding and remember…there is life beyond coding🙂
Did you like it? Share this: