Reputation: 3168
I'm learning how to add JWT token authentication to my webApi. This what I have done so far inside Startup.cs
:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
..
..
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "http://localhost:Port",
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("testPass"))
}
});
app.UseMvc();
}
But I'm getting errors like:
JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470
and
2. JwtBearerOptions' does not contain a definition for 'AutomaticAuthenticate'
Upvotes: 0
Views: 179
Reputation: 16711
You can do this in the ConfigureServices
method in StartUp.cs
.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:Port",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourKey"))
};
});
// other configuration...
}
Then in Configure
method:
app.UseAuthentication();
Upvotes: 1
Reputation:
Try to do it in ConfigureService rather than Configure, try something like
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
It will work!
Upvotes: 0