Difference between revisions of "Token Authentication Using ASP.NET Core"
| (One intermediate revision by the same user not shown) | |||
| Line 374: | Line 374: | ||
== Authorize controllers == | == Authorize controllers == | ||
All controllers decorated by the attribute '''[Authorize]''' are protected by the JWT authentication. | All controllers decorated by the attribute '''[Authorize]''' are protected by the JWT authentication. | ||
| + | |||
| + | You need to pass the token in the HEADER of the request: | ||
| + | Authorization:Bearer <TOKEN> | ||
| + | |||
| + | client.DefaultRequestHeaders.Add("Authorization:Bearer", json.accessToken); | ||
| + | |||
| + | |||
| + | After you revieced your token, you just have to put into Header: | ||
| + | Key: Authorization | ||
| + | Value: Bearer YOUR_TOKEN | ||
| + | including the whitespace between Baerer and your token! | ||
| + | |||
| + | |||
In each http call you need to pass the access_token parmeter: | In each http call you need to pass the access_token parmeter: | ||
http://hostname/controller/route?access_token=MY_TOKEN | http://hostname/controller/route?access_token=MY_TOKEN | ||
The demo code is available on [https://github.com/samueleresca/Blog.TokenAuthGettingStarted Github.] | The demo code is available on [https://github.com/samueleresca/Blog.TokenAuthGettingStarted Github.] | ||
| + | |||
| + | |||
| + | == Checking user authentication and authorisation == | ||
| + | <pre class="brush:csharp;"> | ||
| + | bool isAuthorised = false; | ||
| + | IPrincipal user = HttpContext.User; | ||
| + | if (user.Identity.IsAuthenticated) | ||
| + | { | ||
| + | if (user.IsInRole("Admin")) | ||
| + | { | ||
| + | isAuthorised = true; | ||
| + | } | ||
| + | } | ||
| + | |||
| + | if (!isAuthorised) | ||
| + | { | ||
| + | return BadRequest(ErrorManager.GetError(103)); | ||
| + | } | ||
| + | </pre> | ||
Latest revision as of 12:22, 12 April 2017
Based on this document
Contents
How token based authentication works
Here's the common steps of the token based authentication:
- user requests access by using username / password;
- application provides a signed token to the client;
- client stores that token and sends it along with every request;
- server verifies token and responds with data;
Every single request will require the token. The token should be sent in the HTTP header to keep the idea of stateless HTTP requests.
Setup the project
Once the project is successfully created, add the following configurations to your appsettings.json:
"TokenAuthentication": {
"SecretKey": "secretkey_secretkey123!",
"Issuer": "DemoIssuer",
"Audience": "DemoAudience",
"TokenPath": "/api/token",
"CookieName": "access_token"
}
Tokens transmission / validation
There are two ways to transmit the authorization tokens:
- using HTTP Authorization headers (aka Bearer authentication);
- using browser cookies to save the authentication token;
Bearer token validation
The Microsoft.AspNetCore.Authentication.JwtBearer package enables you to protect routes by using a JWT Token.
To initialize the Bearer authentication you need to split your Startup.cs file and use another partial class, for example Startup.Auth.cs:
public partial class Startup
{
public SymmetricSecurityKey signingKey;
private void ConfigureAuth(IApplicationBuilder app)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = Configuration.GetSection("TokenAuthentication:Audience").Value,
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here:
ClockSkew = TimeSpan.Zero
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
}
}
The Startup.Auth.cs file initialize the Bearer Authentication using configurations defined in the appsettings.json file. The tokenValidationParamaters object will be used also by Cookie validation.
Cookies validation
please check reference web site mentioned above ...
Token generation
There isn't native support to Token generation in ASP.NET Core, but it is possible write a custom token generator middleware from scratch.
Firstly, you need to create a class which implement token options :
using Microsoft.IdentityModel.Tokens;
public class TokenProviderOptions
{
/// <summary>
/// The relative request path to listen on.
/// </summary>
/// <remarks>The default path is <c>/token</c>.</remarks>
public string Path { get; set; } = "/token";
/// <summary>
/// The Issuer (iss) claim for generated tokens.
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// The Audience (aud) claim for the generated tokens.
/// </summary>
public string Audience { get; set; }
/// <summary>
/// The expiration time for the generated tokens.
/// </summary>
/// <remarks>The default is five minutes (300 seconds).</remarks>
public TimeSpan Expiration { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>
/// The signing key to use when generating tokens.
/// </summary>
public SigningCredentials SigningCredentials { get; set; }
/// <summary>
/// Resolves a user identity given a username and password.
/// </summary>
public Func<string, string, Task<ClaimsIdentity>> IdentityResolver { get; set; }
/// <summary>
/// Generates a random value (nonce) for each generated token.
/// </summary>
/// <remarks>The default nonce is a random GUID.</remarks>
public Func<Task<string>> NonceGenerator { get; set; }
= () => Task.FromResult(Guid.NewGuid().ToString());
}
The middleware class will use TokenProviderOptions.cs to generate tokens:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace CustomTokenAuthProvider
{
public class TokenProviderMiddleware
{
private readonly RequestDelegate _next;
private readonly TokenProviderOptions _options;
private readonly JsonSerializerSettings _serializerSettings;
public TokenProviderMiddleware(
RequestDelegate next,
IOptions<TokenProviderOptions> options)
{
_next = next;
_options = options.Value;
ThrowIfInvalidOptions(_options);
_serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
public Task Invoke(HttpContext context)
{
// If the request path doesn't match, skip
if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
{
return _next(context);
}
// Request must be POST with Content-Type: application/x-www-form-urlencoded
if (!context.Request.Method.Equals("POST")
|| !context.Request.HasFormContentType)
{
context.Response.StatusCode = 400;
return context.Response.WriteAsync("Bad request.");
}
return GenerateToken(context);
}
private async Task GenerateToken(HttpContext context)
{
var username = context.Request.Form["username"];
var password = context.Request.Form["password"];
var identity = await _options.IdentityResolver(username, password);
if (identity == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync("Invalid username or password.");
return;
}
var now = DateTime.UtcNow;
// Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims.
// You can add other claims here, if you want:
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
};
// Create the JWT and write it to a string
var jwt = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: now,
expires: now.Add(_options.Expiration),
signingCredentials: _options.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new
{
access_token = encodedJwt,
expires_in = (int)_options.Expiration.TotalSeconds
};
// Serialize and return the response
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
}
private static void ThrowIfInvalidOptions(TokenProviderOptions options)
{
if (string.IsNullOrEmpty(options.Path))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Path));
}
if (string.IsNullOrEmpty(options.Issuer))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Issuer));
}
if (string.IsNullOrEmpty(options.Audience))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Audience));
}
if (options.Expiration == TimeSpan.Zero)
{
throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(TokenProviderOptions.Expiration));
}
if (options.IdentityResolver == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.IdentityResolver));
}
if (options.SigningCredentials == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.SigningCredentials));
}
if (options.NonceGenerator == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.NonceGenerator));
}
}
}
}
The TokenProviderMiddleware class implements the Invoke method to generate tokens by using the TokenProviderOptions. In order to initialize the middleware, it is necessary to modify the Startup.Auth.cs file and add in the ConfigureAuth method:
using System;
using System.Text;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using CustomTokenAuthProvider;
using Microsoft.AspNetCore.Builder;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Options;
namespace Blog.TokenAuthGettingStarted
{
public partial class Startup
{
private void ConfigureAuth(IApplicationBuilder app)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));
// This part to be added
var tokenProviderOptions = new TokenProviderOptions
{
Path = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
Audience = Configuration.GetSection("TokenAuthentication:Audience").Value,
Issuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
IdentityResolver = GetIdentity
};
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = Configuration.GetSection("TokenAuthentication:Audience").Value,
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here:
ClockSkew = TimeSpan.Zero
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
/*
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthenticationScheme = "Cookie",
CookieName = Configuration.GetSection("TokenAuthentication:CookieName").Value,
TicketDataFormat = new CustomJwtDataFormat(
SecurityAlgorithms.HmacSha256,
tokenValidationParameters)
});
*/
app.UseMiddleware<TokenProviderMiddleware>(Options.Create(tokenProviderOptions));
}
private Task<ClaimsIdentity> GetIdentity(string username, string password)
{
// DEMO CODE, DON NOT USE IN PRODUCTION!!!
if (username == "TEST" && password == "TEST123")
{
return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }));
}
// Account doesn't exists
return Task.FromResult<ClaimsIdentity>(null);
}
}
}
The tokenProviderOptions defines the options of the token generator. The IdentityResolver is the Task method which will check the identity of users. For demo purposes, the IdentityResolver is implemented by a simple method called GetIdentity.
Final Steps
Now is possible call the ConfigureAuth method inside the Startup.cs file:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ConfigureAuth(app);
app.UseMvc();
}
Getting token
You can obtain the JWT token by calling the following route /api/token/ using POST and passing the username and password data:
POST api/token Content-Type: application/x-www-form-urlencoded username=TEST&password=TEST123
Authorize controllers
All controllers decorated by the attribute [Authorize] are protected by the JWT authentication.
You need to pass the token in the HEADER of the request:
Authorization:Bearer <TOKEN>
client.DefaultRequestHeaders.Add("Authorization:Bearer", json.accessToken);
After you revieced your token, you just have to put into Header:
Key: Authorization Value: Bearer YOUR_TOKEN
including the whitespace between Baerer and your token!
In each http call you need to pass the access_token parmeter:
http://hostname/controller/route?access_token=MY_TOKEN
The demo code is available on Github.
Checking user authentication and authorisation
bool isAuthorised = false;
IPrincipal user = HttpContext.User;
if (user.Identity.IsAuthenticated)
{
if (user.IsInRole("Admin"))
{
isAuthorised = true;
}
}
if (!isAuthorised)
{
return BadRequest(ErrorManager.GetError(103));
}