Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active January 30, 2020 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/38565c94ff34e403e3ca50965ad855de to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/38565c94ff34e403e3ca50965ad855de to your computer and use it in GitHub Desktop.
JWT Authentication - Startup ConfigureServices Method
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
// configure strongly typed settings objects
var jwtSection = Configuration.GetSection("JwtBearerTokenSettings");
services.Configure<JwtBearerTokenSettings>(jwtSection);
var jwtBearerTokenSettings = jwtSection.Get<JwtBearerTokenSettings>();
var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey);
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 = jwtBearerTokenSettings.Issuer,
ValidateAudience = true,
ValidAudience = jwtBearerTokenSettings.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment