[英]How do I build a custom role based authorization in ASP Core 2?
I have a database that has a user table, access table and a join table assigning a user to multiple access. 我有一个数据库,其中有一个用户表,访问表和一个将用户分配给多个访问权限的联接表。 The site will verify a user by matching the Identity Username from AD with an username in the Users table to verify they can see the site (Intranet).
该站点将通过将AD中的身份用户名与“用户”表中的用户名进行匹配来验证用户,以验证他们可以看到该站点(Intranet)。 The access table is used to specify which pages they are allow to visit.
访问表用于指定允许访问哪些页面。
In ASP Core 2 how can I use Authorization to perform the same check at Startup to verify they are in the Users table and then take it a step further and use Roles to allow the user access to specific web pages. 在ASP Core 2中,如何在启动时使用授权执行相同的检查,以验证它们是否在“用户”表中,然后再进行下一步,并使用“角色”允许用户访问特定网页。
I've gone through the documentation but I can't figure out which way to go as the examples use a login that is not necessary in my case using AD. 我已经阅读了文档,但是由于示例使用的登录名在我使用AD的情况下是不必要的,因此我无法弄清楚该走哪条路。
I have a users table and don't use AD roles because we have a admin for exchange and I do not have access to that. 我有一个用户表,并且不使用AD角色,因为我们有一个管理员可以进行交换,但我无权访问。
Thanks in advance 提前致谢
Authorize attribute is the what you are looking for. 授权属性是您要寻找的。 For example,
例如,
[Authorize(Roles = "Admin, User")]
If you are using OAuth for authentication, you will create a ClaimsIdentity while authenticating. 如果您使用OAuth进行身份验证,则将在身份验证时创建ClaimsIdentity。 Based on the claim, the Authorize attribute will work out of the box.
根据声明,Authorize属性将立即可用。 For example,
例如,
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(oAuthIdentity);
}
You can refer to this post , where I have explained a similar scenario in a bit more detail. 您可以参考这篇文章 ,在这里我已经详细解释了类似的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.