ASP.NET Core flow - datvm/JwtSharp GitHub Wiki
Installing
You need to install the ASP.NET Core package:
Install-Package JwtSharp.AspNetCore
The namespace for Extension method is JwtSharp.AspNetCore
:
using JwtSharp.AspNetCore;
For a full demo project, visit: https://github.com/datvm/JwtSharp/tree/master/Demo/JwtSharp.Demo.AspNetCore
Add Service
Helper Method
You can register the service using the AddJwtIssuerAndBearer
method in the ConfigureServices
(in Startup.cs
):
public void ConfigureServices(IServiceCollection services)
{
// Other services
services.AddJwtIssuerAndBearer(options =>
{
options.Audience = "https://localhost:44375/";
options.Issuer = "https://localhost:44375/";
options.SecurityKey = "PUT-YOUR-KEY-HERE";
});
// Other services
}
AddJwtIssuerAndBearer
helper method explained
The current implementation of AddJwtIssuerAndBearer
does the below task. If it does not work for you, simply put the code with your desired changes instead:
JwtIssuer
to the DI container
Register a singleton of var jwtIssuer = new JwtIssuer(options);
services.AddSingleton(jwtIssuer);
Register Authentication with JwtBearer scheme
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwtOptions =>
{
jwtOptions.TokenValidationParameters = jwtIssuer.TokenValidationParameters;
});
return services;
Register Authentication
Don't forget to register the Authentication middleware in your Configure
method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Other code
app.UseAuthentication();
// Other code
}
Issuing Token
In your Controller
, issue the token using JwtIssuer
instance from the DI. In real cases, you will need to check with your database for real credential checking and issue the Claims that you want.
private readonly JwtIssuer jwtIssuer;
public TestController(JwtIssuer jwtIssuer)
{
this.jwtIssuer = jwtIssuer;
}
[HttpGet, Route("token")]
public IActionResult RequestToken(string username, string password)
{
// Note: this is for testing only, not for production!
// Assume all usernames are valid and password should be password
if (password == "password")
{
var token = this.jwtIssuer.IssueToken(
"id", username,
"username", username,
"loggedInAt", DateTime.UtcNow.ToString("o"),
"isAdmin", (username == "admin").ToString()
);
return this.Ok(new
{
Token = token,
});
}
else
{
return this.BadRequest(new
{
Error = "Incorrect Username or Password",
});
}
}
Authorized Action
For all users
Simply use the normal ASP.NET Core Authentication AuthorizeAttribute
on the methods you desire. In the following example, /authorized
can only be access when there is Bearer Token
in the Authorization
header. A request without valid JWT Bearer token is met with 401 Unauthorized
response.
[Authorize]
[HttpGet, Route("authorized")]
public IEnumerable<KeyValuePair<string, string>> Authorized()
{
return this.User.Claims
.Select(q => new KeyValuePair<string, string>(q.Type, q.Value));
}
With specific Claims
Use the Policy
by ASP.NET Core Authentication for the specific case (for example, Admin-only area, role-based):
Define Policies in Startup
// Add Policy for admin only
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireClaim("isAdmin", "true", "True"));
});
Apply to Action
Use AuthorizeAttribute
with Policy
property to limit an Action
or Controller
. In the following example, /admin
can only be accessed when the Bearer Token has isAdmin
Claim (and its value is "true"
or "True"
) in it.
[Authorize(Policy = "AdminOnly")]
[HttpGet, Route("admin")]
public IEnumerable<KeyValuePair<string, string>> AdminOnly()
{
return this.User.Claims
.Select(q => new KeyValuePair<string, string>(q.Type, q.Value));
}