JWT authentication is a token-based stateless authentication mechanism. It is popularly used as a client-side-based stateless session and it is typically encoded & signed. But how do you decode it? Let’s look at this.
Below, I’ll describe a simple way to read the header and extract an information.
publicstaticstringGetInformationFromToken(HttpContextcontext,stringdataProp){vartoken=GetJwtTokenFromRequest(context);if(string.IsNullOrEmpty(token)){//token is empty, returning nullreturnnull;}try{vartokenHandler=newJwtSecurityTokenHandler();tokenHandler.ValidateToken(token,newTokenValidationParameters{ValidateIssuerSigningKey=true,ValidateIssuer=false,ValidateAudience=false},outSecurityTokenvalidatedToken);varjwtToken=(JwtSecurityToken)validatedToken;//the JwtSecurityToken contains a property "Claims" from which you extract a data property that you want to readvartargetInfo=jwtToken.Claims.FirstOrDefault(c=>c.Type==dataProp);if(targetInfo!=null){returntargetInfo.Value;}returnnull;}catch(Exceptione){// Token validation failedreturnnull;}}