• This repository has been archived on 27/Apr/2023
  • Stars
    star
    288
  • Rank 143,151 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sample middleware component for ASP.NET that generates JWT access tokens

Simple Token Provider Middleware for ASP.NET

⚠️ Deprecated: This project and the concepts it uses are outdated!

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 middleware

The 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:

  • Path (optional) - The endpoint path relative to the server root. Default: /token
  • Audience - The JWT aud claim value.
  • Issuer - The JWT iss claim value.
  • Expiration (optional) - The expiration duration for new tokens. Default: 5 minutes
  • SigningCredentials - The signing credentials to use when signing new tokens.
  • IdentityResolver - A delegate that takes a username/password and returns a ClaimsIdentity if the user exists, or null if the user does not exist.
  • NonceGenerator (optional) - A delegate that generates a random value (nonce) for each new token. Default: 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);
}

How it works

At a high level, the middleware does the following:

  • Intercepts requests to options.Path
  • Verifies the request is a POST with Content-Type: application/x-www-form-urlencoded
  • Pulls the username and password out of the form body
  • Delegates to options.IdentityResolver to look up the user; errors if the credentials are bad
  • Creates a JWT with the following claims:
    • sub (subject) - the username
    • jti (nonce) - a random value
    • iat (issued-at) - the current time
    • nbf (not-before) - the current time
    • exp (expiration) - the current time + options.Expiration
    • iss (issuer) - options.Issuer
    • aud (audience) - options.Audience
  • Encodes the JWT to a string and sends it back to the client

Trying it out

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.

Acknowledgements

These resources were extremely helpful as I was figuring out how to make this work:

More Repositories

1

little-aspnetcore-book

The Little ASP.NET Core Book, a friendly introduction to web programming and ASP.NET Core 2.0
702
star
2

BeautifulRestApi

Beautiful REST API design with ASP.NET Core and Ion
C#
598
star
3

oidc-debugger

OAuth 2.0 and OpenID Connect debugging tool
HTML
221
star
4

little-aspnetcore-todo

Example project from The Little ASP.NET Core Book
C#
221
star
5

QuestionExchange

Multi-tenant application architecture with ASP.NET Core 2.0 + SaasKit + PostgreSQL + Citus
C#
25
star
6

ApiSecurity

Helpers for building secure APIs with ASP.NET Core
C#
14
star
7

csharp-travis-example

An example of using Travis-CI and Mono to run unit tests for a C# project
C#
13
star
8

AlexaHelloWorld.NET

Simple example of using C# and AWS Lambda to power an Alexa skill
C#
12
star
9

Iso8601kit

Easily convert to and from ISO 8601 duration strings from .NET
C#
12
star
10

SHOUTCLOUD.NET

ASYNCHRONOUS WEBSCALE UPPERCASE AS A SERVICE
C#
5
star
11

simple-linq

A very simple LINQ provider
C#
4
star
12

circleci-aspnetcore

Demo of CircleCI building an ASP.NET Core project
C#
3
star
13

FlexibleConfiguration

Configure a .NET application from a variety of sources
C#
3
star
14

Jobinator

A small hobby project: Angular SPA + .NET backend + OWIN authentication, all to tag job title strings
C#
3
star
15

RocketCalendarSkill

An Alexa skill that tells you about upcoming rocket launches πŸš€
C#
2
star
16

gpg-and-friends

A shared playground for signed commits
2
star
17

okta-dotnet-password-token-example

An example of using the Okta OAuth2 API to generate a JWT for a user
C#
2
star
18

recaffeinate.co

Nate's website and blog β˜•οΈ
HTML
2
star
19

HelloCoreWorld

PowerShell
1
star
20

stormpath-aspnet-webapi-bearer-example

Example of using Stormpath to secure Web API with Bearer JWTs
C#
1
star
21

git-aliases

1
star
22

AlexaHelloWorldNode

Simple example of using Node, JavaScript, and AWS Lambda to power an Alexa skill
JavaScript
1
star
23

stormpath-aspnet-mvc-identity-example

Example of using Stormpath as an ASP.NET Identity 2.0 provider
C#
1
star
24

polyglot-dotnet

Determine the source language of a .NET assembly
C#
1
star
25

okta-aspnetcore-social-login-example

Okta + social login + account linking
C#
1
star
26

holidaycheer.xyz

Spreading holiday cheer
HTML
1
star