I have a Jwt Bearer token that I am storing in Session in my .Net Core 2.1 app. In my middleware I am intercepting the request and attaching the token to the headers by:
httpContext.Request.Headers.Add("Authorization", $"Bearer {token}");
This is currently not working as I am getting an unauthorized on the protected route. If I make the same call using postman and passing in Authorization and Bearer token in the headers, it works.
What do I need to change to the http.Request to make it acceptable?
Portion of startup with Jwt: var signingKey = key;
services.AddSingleton<IJwtFactory, JwtFactory>();
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = Issuer;
options.Audience = Audience;
options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Issuer,
ValidateAudience = true,
ValidAudience = Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
})
.AddCookie(cfg => cfg.SlidingExpiration = true);
Configure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
app.UseAuthentication();
app.UseStaticFiles();
app.UseSession();
app.UseHttpContextLogging();
app.ConfigureErrorHandling(env);
app.UseSiteRouteMiddleware(getRoutes); -- Middleware that intercepts the request, adding the token here
app.UseRequestLocalization();
app.UseRewriter();
app.UseMvc(getRoutes);
}