簡體   English   中英

如何在ASP Core 2中建立基於角色的自定義授權?

[英]How do I build a custom role based authorization in ASP Core 2?

我有一個數據庫,其中有一個用戶表,訪問表和一個將用戶分配給多個訪問權限的聯接表。 該站點將通過將AD中的身份用戶名與“用戶”表中的用戶名進行匹配來驗證用戶,以驗證他們可以看到該站點(Intranet)。 訪問表用於指定允許訪問哪些頁面。

在ASP Core 2中,如何在啟動時使用授權執行相同的檢查,以驗證它們是否在“用戶”表中,然后再進行下一步,並使用“角色”允許用戶訪問特定網頁。

我已經閱讀了文檔,但是由於示例使用的登錄名在我使用AD的情況下是不必要的,因此我無法弄清楚該走哪條路。

我有一個用戶表,並且不使用AD角色,因為我們有一個管理員可以進行交換,但我無權訪問。

提前致謝

授權屬性是您要尋找的。 例如,

[Authorize(Roles = "Admin, User")]

如果您使用OAuth進行身份驗證,則將在身份驗證時創建ClaimsIdentity。 根據聲明,Authorize屬性將立即可用。 例如,

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);
    }

您可以參考這篇文章 ,在這里我已經詳細解釋了類似的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM