0
votes

I am having some trouble implementing JWT token authentication in .NET Core 2.0. There are a number of blog posts online that I have read, however they are mostly now outdated as they're for .NET Core 1.x.

I have also found it difficult to find any documentation on how to generate and issue a token. In .NET Framework Web API this was all 'magically' handled with framework code.

I am building an API with custom identity entities and custom store implementation, and an Angular front end.

I am look for a way to generate a token in the API with a '/token' endpoint and then authenticate and authorize requests when the token is passed in via the Authorizaton: Bearer {token} header in http requests?

2

2 Answers

0
votes

in Startup.cs -> ConfigureServices, add in the following, updating with your settings:

services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Audience = "your audience";
options.ClaimsIssuer = "claims issuer";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "claims issuer",
IssuerSigningKey = { your signing key }
};
});

Next up, in Configure:

app.UseAuthentication();
app.UseMvc();

You have to make sure that UseAuthentication is BEFORE UseMvc for it to work.

Basically everything that was previously in the Configure method has now been moved to the Services section :)

Check out this blog post for an example, as well as a link to a repo where you can get the example project: Shawn Wildermuth's Blog

0
votes

Use below link for implementation..

Part I

Part II

Just that for the authorization use authorize attribute as

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

because we have registered a separate authentication schemes in the startup.cs and hence the cookies will be created for JwtBearerDefaults.AuthenticationScheme.