At the time it was created, there weren't many resources available for token authentication in early ASP.NET Core. Nowadays, I would not recommend doing this yourself!
Here are some resources for doing token authentication in modern ASP.NET Core:
This project demonstrates how to generate JSON Web Tokens (JWTs) for token authentication in ASP.NET Core RC2. The functionality is wrapped up in a reusable middleware component.
Original blog post: Token Authentication in ASP.NET Core
This has not been tested in production, so explore and use at your own risk!
Configuring the middlewareThe token provider endpoint can be added to your pipeline in Configure()
:
app.UseSimpleTokenProvider(new TokenProviderOptions { Path = "/api/token", Audience = "ExampleAudience", Issuer = "ExampleIssuer", SigningCredentials = signingCredentials, IdentityResolver = GetIdentity });
The options are:
/token
aud
claim value.iss
claim value.ClaimsIdentity
if the user exists, or null
if the user does not exist.Guid.NewGuid()
If you are using an HMAC-SHA256 key (symmetric signing), the SigningCredentials
will look like:
// The secret key every token will be signed with. // Keep this safe on the server! var secretKey = "mysupersecret_secretkey!123"; var signingCredentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)), SecurityAlgorithms.HmacSha256);
The IdentityResolver
delegate abstracts away the concern of looking up and verifying a user given a username and password. If the user exists and the password is valid, a ClaimsIdentity
should be returned. If not, the delegate should return null.
You can use the following dummy resolver for testing: (don't use in production!)
private Task<ClaimsIdentity> GetIdentity(string username, string password) { // Don't do this in production, obviously! if (username == "TEST" && password == "TEST123") { return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { })); } // Credentials are invalid, or account doesn't exist return Task.FromResult<ClaimsIdentity>(null); }
At a high level, the middleware does the following:
options.Path
Content-Type: application/x-www-form-urlencoded
options.IdentityResolver
to look up the user; errors if the credentials are badsub
(subject) - the usernamejti
(nonce) - a random valueiat
(issued-at) - the current timenbf
(not-before) - the current timeexp
(expiration) - the current time + options.Expiration
iss
(issuer) - options.Issuer
aud
(audience) - options.Audience
You can install the middleware in a new project, or just run the included test project. Send a POST request using a tool like Fiddler or Postman:
POST /token (or whatever you set options.Path to)
Content-Type: application/x-www-form-urlencoded
username=TEST&password=TEST123
You should get a 200 OK
response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJURVNUIiwianRpIjoiYzRjYzdhMmUtMjI0OS00ZWUzLWJkM2MtYzU5MDkzYmU5MGU1IiwiaWF0IjoxNDYzNTMwMDI0LCJuYmYiOjE0NjM1MzAwMjMsImV4cCI6MTQ2MzUzMDMyMywiaXNzIjoiRXhhbXBsZUlzc3VlciIsImF1ZCI6IkV4YW1wbGVBdWRpZW5jZSJ9.mI0NPO437IuBSt5kmayy5XhNFEHVF4IyMkKsmtas6w8",
"expires_in": 300
}
You can try decoding and verifying the JWT at jsonwebtoken.io.
These resources were extremely helpful as I was figuring out how to make this work:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4