Hot Chocolate GraphQL Custom Authentication Series Using Pure Code First Technique - Part3 -Validating JWT Token And Different Authorization Techniques
Part2 we had generated a JWT access token for the user authentication. In this article, we are going to validate the JWT access token and also understand different techniques of Authorization.
Install JwtBearer NuGet:
To enable jwt token validation service we have to install JwtBearer NuGet.
Package Manager Command: Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 5.0.4
.Net CLI Command: dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 5.0.4
Register JwtBearer Service:
In the 'Startup.cs' file, we should register our JwtBearer validation service.
Startup.cs:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { var tokenSettings = Configuration .GetSection("TokenSettings").Get<TokenSettings>(); options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = tokenSettings.Issuer, ValidateIssuer = true, ValidAudience = tokenSettings.Audience, ValidateAudience = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key)), ValidateIssuerSigningKey = true }; });
- (Line: 1) We specified the name of authentication like 'Bearer' to the 'AddAuthentication()' method.
- The 'TokenValidationParameter' instance initialized with the key configurations like 'Issuer', 'Audience', 'Key'. So on receiving the jwt auth token server will validate it with this ' TokenValidationParameters'.
Add Authentication Middleware:
In the 'Startup.cs' file, add the authentication middleware just above the authorization middleware.
Startup.cs:
app.UseAuthentication(); app.UseAuthorization();
Install Hot Chocolate Authorization NuGet:
Package Manager Command: Install-Package HotChocolate.AspNetCore.Authorization -Version 11.0.9
.Net CLI Command: dotnet add package HotChocolate.AspNetCore.Authorization --version 11.0.9
Register GraphQL Authorization Service:
In the 'Startup.cs' file, register the GraphQL authorization service.
Startup.cs:
services.AddGraphQLServer() .AddQueryType<QueryResolver>() .AddMutationType<MutationResolver>().AddAuthorization();
Implement Basic Authorization:
In GraphQL using the code first technique, it is quite easy to enable authorization per resolver. Just decorate the required resolvers or methods with [HotChocolate.AspNetCore.Authorization.Authorize] attribute.
Recall Part1, we created a resolver or method like 'Welcome' in Query type(QueryResolver.cs). So let's make this method secured, we can do it by applying the 'Authorize' attribute on top of the resolver.
Resolvers/QueryResolver.cs:
[Authorize] public string Welcome() { return "Welcome To Custom Authentication Servies In GraphQL In Pure Code First"; }Now try to consume the 'Welcome' resolver without the jwt token.Now try to consume the 'Welcome' resolver using the jwt token value in the authorization header. (Note: in authorization header, jwt token must be prefixed with 'bearer' keyword).
Roles Based Authorization:
Recall Part2, our jwt token contains claims like 'LastName', 'Email', and all user roles. So based on these claims we can protect our resources.
Actually, user claims mean key and value pair. Roles are also claims, but here all claims will have the same key called 'Roles'.That means roles are like one key and an array of values. So using roles we are able to restrict resource consumption.
So implementing roles base authorization very simple. For the 'Authorize' attribute we have to specify array roles. So the user must contain at least one role value from the array to consume the resource.
Resolvers/QueryResolver.cs:
[Authorize(Roles= new[] {"admin","super-admin"})] public string Welcome() { return "Welcome To Custom Authentication Servies In GraphQL In Pure Code First"; }
Policy-Based Roles Authorization:
It is one more way to enable authorization. In this approach, we have to define a policy in 'startup.cs', and in the requirements need to specify the role values. Now in the authorization attribute, we need to use the name of the policy. So user contains at least one role value that is registered in the policy.
Startup.cs:
services.AddAuthorization(options => { options.AddPolicy("roles-policy", policy => { policy.RequireRole(new string[]{"admin","super-admin"}); }); });Resolvers/QueryResolver.cs:
[Authorize(Policy="roles-policy")] public string Welcome() { return "Welcome To Custom Authentication Servies In GraphQL In Pure Code First"; }
Policy-Based Claims Authorization:
We can authorize the user with his claims by implementing policy. In claims-based authorization, we can just check the key name of the claims that existed or not. We know our jwt token contains 'LastName' and 'Email' as claims. Now we can enable authorization like the user should have a claim name like 'LastName' independent of its value.
Startup.cs:
services.AddAuthorization(options => { options.AddPolicy("roles-policy", policy => { policy.RequireRole(new string[]{"admin","super-admin"}); }); options.AddPolicy("claim-policy-1", policy => { policy.RequireClaim("LastName"); }); });
- So here resolvers with authorization policy "claim-policy-1" only allows with the user having claim name like 'LastName'
[Authorize(Policy="claim-policy-1")] public string Welcome() { return "Welcome To Custom Authentication Servies In GraphQL In Pure Code First"; }Another approach to enable claims authorization with the values of the claim. In this approach, we define a group of values for a claim and the user must have at least one value to be authorized.
Startup.cs:
services.AddAuthorization(options => { options.AddPolicy("roles-policy", policy => { policy.RequireRole(new string[]{"admin","super-admin"}); }); options.AddPolicy("claim-policy-1", policy => { policy.RequireClaim("LastName"); }); options.AddPolicy("claim-policy-2", policy=>{ policy.RequireClaim("LastName",new string[]{"Bommidi","Test"}); }); });Resolvers/QueryResolver.cs:
[Authorize(Policy="claim-policy-2")] public string Welcome() { return "Welcome To Custom Authentication Servies In GraphQL In Pure Code First"; }So that's all about jwt token validation and different authorization techniques.
Video Session:
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on validating JWT token and different Authorization techniques in the Pure Code First technique in Hot Chocolate GraphQL. I love to have your feedback, suggestions, and better techniques in the comment section below.
Another excellent post. Thank you.
ReplyDeleteThanks.
ReplyDelete