There are multiple ways to enable authentication in Hot Chocolate. Here is simple approach:
Step 1 – Enable ASP.NET Core authentication
First step is to enable authentication at ASP.NET Core level. Let’s use JWT token for authentication:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.UseAuthentication(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services | |
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | |
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options)); |
Step 2- Enable authentication at the root GraphQL query
The second(and already the last step) is to enable authentication on the root query type. By providing no role or policy names we’re simply saying the user must be authenticated.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RootQueryType : ObjectType<Query> | |
{ | |
protected override void Configure(IObjectTypeDescriptor<Query> descriptor) | |
{ | |
descriptor.Authorize(); | |
} | |
} |