gpt4 book ai didi

c# - Owin 授权拒绝角色

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:25 27 4
gpt4 key购买 nike

我最近加入了一个项目团队,负责为项目后端设置用户角色。它使用带有 Owin 的 ASP.NET C# WebApi。我的问题是,当我像这样将属性分配给 Controller 方法时:

[Authorize(Roles = "Admin")]

对于此请求,响应始终是授权被拒绝。但是,如果我只是使用:

[Authorize]

它有效。请注意,我正在使用已分配管理员角色的用户登录。

我注意到这个问题类似于:Authorization roles WebAPI oauth owin

但是,他们在 startup.cs 中的代码似乎有所不同,否则我很难正确地遵循答案。

我必须使用的 startup.cs 中的代码是:

public void Configuration(IAppBuilder app)
{
// configure OAuth
ConfigureOAuth(app);

// configure Mvc
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}

public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

我是否需要在此处添加其他内容以允许角色,或者它应该在代码中的其他地方。我不完全熟悉 ASP.NET C# MVC 或 WebApi,非常感谢任何帮助。

最佳答案

SimpleAuthorizationServerProvider

你有类似GrantResourceOwnerCredentials的方法

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
await Task.Run(
() => {
...logging logic...
var loginResult = authRepository.Login(context.UserName, context.Password);
if (!loginResult.Success) return;
...logging logic...

var claims = new List < Claim > ();
claims.add(new Claim(ClaimTypes.Role, loginResult.Role)); < --here
var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ExternalBearer);
context.Validated(id);
});
}

loggingResult 是由您的存储库/DAL 层返回的内容

关于c# - Owin 授权拒绝角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38140786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com