Implement JWT In .NET Core 3.1 API

INexLin
3 min readOct 27, 2020

--

What is JWT?

  • JWT is an abbreviation of JSON Web Token. It is an open standard (RFC 7519) based on JSON format
  • JWT can be signed using HMAC、RSA、ECDS
  • We usually use JWT for authentication. A simple scenario using JWT as below:
  1. authentication: Client provides valid username and password to Authentication Center. Usually it happens in Login.
  2. JWT Token: When client was authenticated. Authentication Center response a valid JWT to client.
  3. Valid JWT, Response Resource: Client request resource using valid JWT. Resource server response resource to client.
  4. Invalid JWT, Unauthorized response: Usually JWT include expired time. If client send expired JWT or invalid JWT, resource server response authorized request.

JWT Structure

JWT is composed by three JSON objects and using “.” to separate.

xxxxxx.yyyyyy.zzzzzz
  • Header(xxxxxx)

The type of Token and what kind of algorithm used for signing such as HMAC、RSA or ECDS.

{‘typ’: ‘JWT’,‘alg’: ‘HS256’}

Then the first part JSON used Base64 to encode

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
  • Payload(yyyyyy)

The second part contains claims for transmitting information. There are three types of claims:

  1. Registered claims: Predefine claims that are not mandatory but recommended such as iss(Issuer), exp(Expiration Time). There are more details and claims in RFC 7519.
  2. Public claim
  3. Private claim: Custom claim that usually contain not sensitive information about user such as user role or user name.
  • Signature(zzzzzz)

The signature is created by base64(header), base64(payload) and secret with encrypted algorithm.

HMACSHA256(
base64UrlEncode(header) + “.” +
base64UrlEncode(payload),
secret)

Implement JWT In .NET Core 3.1 API

  • Install required a package of JWT from NuGet Package:
Microsoft.AspNetCore.Authentication.JwtBearer
  • Add authentication middleware in Startup
  1. ConfigureServices

2. Configure

Set up Authentication middleware. It’s important to set up UseAuthentication before UseAuthorization or you will get error in authenticated flow.

3. Add “JWTSettings” region for setting up “Issuer”, “SecretKey” in appsettings

“JWTSettings”: {“Issuer”: “JwtNetCore”,“Audience”: “JwtNetCore”,“SecretKey”: “djlfsjdlkfjlkewjrliew”,“ExpireMinutes”: “5”}

4. Before we create Login API, we need to create “GenerateJWTToken” method in TokenHelper class. In TokenHelper class, we dependency injection configuration for getting JWTSettings.

5. In this step we will create AuthController with Authorize attribure. There are Login API and GetClaims API inside the AuthController. Login API don’t need to authenticate JWT token but GetClaims API need it. Therefore, we put “AllowAnonymous” attribute above Login API. When user had authorized, Login API response JWT token to client.

6. Let’s Test with Postman

  • Login API
  • GetClaims

Success

Fail

view all code in github

--

--