Creating JWT -
- Import “Microsoft.AspNetCore.Authentication.JwtBearer” package from Nuget.
- Select the algorithm. like HMACSHA256.
- Creating the claims collection. Remember there are standard claims and you can add your own.
- Create credentials object using algo and secret key.
- Generate token using claims and credentials.
- Add [Authorize] attribute to controller, then action methods of this controller will be authorized.
JWT token has this format: Header.payload.signature
Header: Contains algorithm used to create JWT like HSA256
Payload: Contains information related to user and authentication
Signature: Created using Header and payload
JWT is encoded not encrypted, so never put critical information in it.
JWT is encoded not encrypted, so never put critical information in it.
Validating JWT token in middleware
Refresh Token: This is sent by server along with jwt, when jwt expired client sends this refresh token to server and server generate new JWT and refresh token and sends to client.
Benefit of refresh token is that again and again client no need to send user credentials.
Storing JWT at client end:
In-memory: Using the application variable we can store the token when the application is running. this is for application session only.
Cookie: If you want to store beyond application session(log time). cookie is a good place.
Indexed DB, Session storage and local storage are prone to XSS attacks.
Cookie: If you want to store beyond application session(log time). cookie is a good place.
Indexed DB, Session storage and local storage are prone to XSS attacks.
Create cookie using HTTP only. By doing so this cookie can not be read using JavaScript
“document.cookie”. In other words cookie is safe from XSS attacks.
Below could be third party Google, amazon, facebook or self owned services -
Open Id: Used for authentication, you want to just know if the user exists in the system in or not. Like shopping
sites , mobile applications , single sign on etc.
OAUTH: Used for authorization, when third party application tries to access resources.
Open ID Connect: Used for authentication plus authorization both, when you want to authenticate and authorize as well like intranet websites.
Identity Server: This is a free open source server that you can use to implement Open Id Connect and Auth. It is certified by OpenId Foundation.
Single Sign on: Organizations those use single sign on, they redirects requests to their Identity server from each of their web portals, user get authenticated get token from Identity server and can access the web portals.
Identity server could a third party like Okta.
Identity server could a third party like Okta.