簡體   English   中英

ASP.NET Core 2.0無法在Razor視圖或控制器[authorize]注釋中檢查用戶是否正確處於角色中

[英]ASP.NET Core 2.0 unable to check if user is in role properly in Razor view or controller [authorize] annotation

我正在研究基於角色授權的遺留項目,但我遇到了一些問題。 User.IsInRole("admin")[Authorize(Roles = "admin")]始終未通過授權。 User.IsInRole()始終返回False 我很確定用戶已正確添加到角色中。 Role name 'admin' is already taken. User already in role 'admin'.

也許一些服務正在影響另一個。

這是我的startup.cs恢復代碼:

public void ConfigureServices(IServiceCollection services){

    services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connetctionString));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomUserClaimsPrincipalFactory>();
    services.AddMvc();
    services.AddDistributedMemoryCache();
    services.AddSession();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc(routes => {...});
}

我錯過了什么?

PS。 是的,我記錄了你並登錄。

PS。 是的,用戶是管理員角色

PS。 “admin”以小寫形式正確

PS。 ApplicationDbContext繼承IdentityDbContext

PS2。 這是我的數據

SELECT id,username FROM aspnetusers;

|id          | username        |
|c4f7bf16... | admin@admin.com |

SELECT Id,Name FROM aspnetroles;

|Id          | Name  |
|50e2a572... | admin |

SELECT * FROM aspnetuserroles;

|UserId      | RoleId     |
|c4f7bf16... | 50e2a572...|

我有一種感覺,這是因為你的Roles ,你的Claims是什么地方混了。

根據文檔 ,ClaimsPrincipal.IsInRole()方法檢查ClaimsIdentity.RoleClaimType類型的ClaimsIdentity.RoleClaimType

可以設置“admin”聲明,而不是ClaimType ClaimsIdentity.RoleClaimType在這種情況下,它將失敗身份驗證。

身份服務器配置為在身份驗證后返回聲明中的角色。您可以在控制器中檢查聲明。

像這樣

var claims = User.Claims.ToList();

在經歷了很多錯誤后,我終於找到了我所缺少的東西。

我只擴展了UserClaimsPrincipalFactory<ApplicationUser>而不是UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>

正確擴展后,角色能夠成為責任人。

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>

確保您的ApplicationDbContext繼承IdentityDbContext

public class ApplicationDbContext: IdentityDbContext<ApplicationUser>

您的問題可能還有一個,請檢查您的角色名稱是否為admin

對於AuthorizeUser.IsInRole ,它區分大小寫,這意味着如果您的角色名稱為Admin ,則User.IsInRole("admin")[Authorize(Roles = "admin")]將失敗。

要檢查它是否為admin ,請嘗試await _userManager.IsInRoleAsync(user, "user")

        var user = await _userManager.FindByNameAsync(User.Identity.Name);

        var r1 = User.IsInRole("User");
        var r2 = User.IsInRole("user");
        var r3 = await _userManager.IsInRoleAsync(user, "user");

您可以嘗試將role定義為const以避免大小寫不匹配。

以下是一些可用於檢索用戶或組角色的有用方法:

ApplicationGroupManager gm = new ApplicationGroupManager();

// Returns Role Name by using Role Id parameter
string roleName = RoleManager.FindById("").Name; 

// Returns Group Id and Role Id by using User Id parameter
var userGroupRoles = gm.GetUserGroupRoles(""); 

// Returns Group Roles by using Group Id parameter
var groupRoles = gm.GetGroupRoles(""); 

// Assing Group Role Names to a string array
string[] groupRoleNames = groupRoles.Select(p => p.Name).ToArray(); 


//###############################################################################################

/* Assign Default ApplicationGroupRoles to the User. As the default roles are already defined 
to the User after the first login to the system, there is no need to check if the role is NULL 
(otherwise it must be checked!!!) */

// Returns Group Roles by using Group Id parameter
var groupRoles = groupManager.GetGroupRoles("751b30d7-80be-4b3e-bfdb-3ff8c13be05e"); 

// Returns Group Roles by using Group Id parameter (Asynchronous method)
var groupRoles = await groupManager.GetGroupRolesAsync("751b30d7-80be-4b3e-bfdb-3ff8c13be05e"); 

//Assign ApplicationGroupRoles to the User
foreach (var role in groupRoles)
{
    string roleName = RoleManager.FindById(role.Id).Name;
    UserManager.AddToRole(user.Id, roleName);
}


另一方面,User.IsInRole()可以在HTML字符串(對於Razor View側)有條件地使用(即DataTable),可以使用以下方法:

@*Display Operations button according to the user roles:*@
@{
    string canView = Request.IsAuthenticated && User.IsInRole("CanViewTeam") ? "true" : "false";
}

<script>
    // assign C# variable to JavaScript variable.
    var CanView = @Html.Raw(@canView); 

    var table;

    $(document).ready(function () {

        table = $('#dtbTeam').DataTable({ 

            //Code omitted for brevity

            "render": function (data, type, full, meta) {
                var renderHtml = '';
                if(CanView){
                    renderHtml += '<a title="Details" id="lnkDetails" ></i></a>';
                }
                return renderHtml;
            }
        });             

    });
</script>

希望這可以幫助...

暫無
暫無

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

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