Checking login user AuthorizePolicy in Razor page on Asp.Net Core

非 Y 不嫁゛ 提交于 2019-12-04 23:38:09
James P

This seems similar to question asked here

I found this link which may be helpful: https://docs.asp.net/en/latest/security/authorization/views.html

Examples from that page:

@if (await AuthorizationService.AuthorizeAsync(User, "PolicyName"))
{
    <p>This paragraph is displayed because you fulfilled PolicyName.</p>
}

In some cases the resource will be your view model, and you can call AuthorizeAsync in exactly the same way as you would check during resource based authorization;

@if (await AuthorizationService.AuthorizeAsync(User, Model, Operations.Edit))
{
    <p><a class="btn btn-default" role="button"
    href="@Url.Action("Edit", "Document", new {id= Model.Id})">Edit</a></p>
}

With Dot net core 2.0 AuthorizationService.AuthorizeAsync no longer returns a boolean, it returns a AuthorizationResult. A working version for dot net core 2.0 will be something like this:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@if ((await AuthorizationService.AuthorizeAsync(User, "RequireAuthenticatedUser")).Succeeded)
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

Therefore the complete view contains:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

// Your HTML elements and i.e.:
@if (await AuthorizationService.AuthorizeAsync(User, "RequireAuthenticatedUser"))
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

To put it even more succinctly:

@inject Microsoft.AspNetCore.Authorization.IAuthorizationService authorizationService

@if (await authorizationService.AuthorizeAsync(User, null, "RequireAuthenticatedUser"))
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

It appears AuthorizeAsync() requires the resource parameter, but null can be passed as in my example.

If you're going to use this in many views, then you'd better implement a custom RazorPage:

public abstract class MyRazorPage<T> : RazorPage<T>
{
    public async Task<bool> HasPolicyAsync(string policyName)
    {
        var authorizationService = Context.RequestServices.GetService(typeof(IAuthorizationService)) as IAuthorizationService;
        bool isAdmin = (await authorizationService.AuthorizeAsync(User, policyName)).Succeeded;
        return isAdmin;
    }
}

then open _ViewImports.cshtml and add the next instruction:

@inherits MyRazorPage<TModel>

now you can call HasPolicyAsync() method from any view:

    if (await HasPolicyAsync(Policies.RequireAdmin))
    {
        <h2>Admin is authorized</h2>
    }

It would look much more concise.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!