介绍
文本说一下认证和授权,因为GraphQL的特殊性他不能直接使用微软提供的授权来做
正文
关于认证我这边没有自己写,我采用了okta提供的第三方认证服务,
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
options.DefaultChallengeScheme = OktaDefaults.ApiAuthenticationScheme;
options.DefaultSignInScheme = OktaDefaults.ApiAuthenticationScheme;
}).AddOktaWebApi(new OktaWebApiOptions()
{
OktaDomain = "https://dev-xxxx.okta.com",
AuthorizationServerId = "default",
Audience = "api://default",
});
builder.Services
.AddGraphQLServer()
.AddQueryType<PostQuery>()
.AddMutationType<PostMutation>()
.AddSubscriptionType<PostSubscription>()
.AddAuthorization()
app.UseAuthentication();
[UsePaging]
[UseOffsetPaging]
[UseProjection]
[UseFiltering]
[UseSorting]
[Authorize]
public IExecutable<Post> GetPosts([Service] DbContext db)
{
return db.Post.AsExecutable();
}
我们先不加认证Jwt来调用下接口,可以发现提示没有权限
当我我们加上Jwt后
接下来我们加上授权看看,我们做一个简单的策略授权。
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("HasCountry", policy =>
policy.RequireAssertion(context =>
context.User.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/scope")));
});
app.UseAuthorization();
[Authorize(Policy = "HasCountry")]
public class PostQuery
{
[UsePaging]
[UseOffsetPaging]
[UseProjection]
[UseFiltering]
[UseSorting]
[Authorize]
public IExecutable<Post> GetPosts([Service] DbContext db)
{
return db.Post.AsExecutable();
}
}
认证授权的教程就先到这,这是一个非常简单的例子,GraphQL厉害的是可以对字段进行授权,我们高级篇再说
结语
本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用
联系作者:加群:867095512 @MrChuJiu
标签:MongoDb,db,认证,public,GraphQL,Net6,授权,options From: https://www.cnblogs.com/MrChuJiu/p/17165929.html