gpt4 book ai didi

c# - 授权具有角色的属性不起作用?

转载 作者:行者123 更新时间:2023-11-30 15:27:49 26 4
gpt4 key购买 nike

我正在努力让它工作,但到目前为止运气不好。我的 Authorize 属性独立工作,但是一旦我声明了用户必须属于的角色,我就会从我的 webapi 返回以下消息

{"message":"Authorization has been denied for this request."}

启动.cs

public void Configuration(IAppBuilder app)
{
//HttpConfiguration config = new HttpConfiguration();

ConfigureOAuth(app);

// simple injector
SimpleInjectorConfig.Register();

AutoMapperConfig.RegisterMappings();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}

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

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

}

SimpleAuthorizationServerProvider.cs

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private AccountService _service;

public SimpleAuthorizationServerProvider(AccountService service)
{
_service = service;
}

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}


public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

User user = await _service.FindUserAsync(context.UserName, context.Password);

if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}


var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
//identity.AddClaim(new Claim("role", "user"));

context.Validated(identity);

}
}

装饰 Controller 方法,我使用

[Authorize(Roles="CanViewCompany")]

如果我只使用它,它会工作并返回我期望的数据

[Authorize]

我的基本用户类

public class User : IdentityUser<long, UserLogin, UserRole, UserClaim>, IUser<long>
{
public User()
: base()
{
this.Groups = new HashSet<UserGroup>();
}

public virtual ICollection<UserGroup> Groups { get; set; }

}

我确信我遗漏了什么,但我不确定是什么。非常感谢任何帮助

最佳答案

似乎是这个函数导致了错误。我没有设置用户名(这并没有破坏它,但是 User 属性没有,我相信我将来会需要)。

此外,我没有添加任何角色。我不确定这是否是解决此问题的正确方法,但它确实有效。

如果有人知道更好/正确的方法,请告诉我。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

User user = await _service.FindUserAsync(context.UserName, context.Password);

if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}

var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "CanViewCompany"));
identity.AddClaim(new Claim(ClaimTypes.Role, "CanAddCompany"));
identity.AddClaim(new Claim(ClaimTypes.Role, "CanEditCompany"));
identity.AddClaim(new Claim(ClaimTypes.Role, "CanDeleteCompany"));

context.Validated(identity);

}

关于c# - 授权具有角色的属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847048/

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