2016-05-29 50 views

回答

12

這似乎類似的問題問here

我發現這個鏈接,可能會有所幫助:https://docs.asp.net/en/latest/security/authorization/views.html

例子從該頁面:

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

在某些情況下,資源將成爲您的視圖模型,您可以按照與在 基於資源的授權期間檢查完全相同的方式撥打 AuthorizeAsync;

@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> 
} 
+9

這太好了。 :D對於下一個尋找這個你需要'@使用Microsoft.AspNetCore.Authorization'和'@inject IAuthorizationService AuthorizationService'以及 –

+0

@Thomas感謝您將使用...子句放入此答案,MS忘記了重要的一點信息在他們的文檔中。 – JReam

+0

@JReam hehe yea我只是希望人們能夠提出問題而不是評論:P –

4

因此,完整的視圖包含:

​​
0

要說得更爲簡潔:

@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> 
} 

看來AuthorizeAsync()需要的資源參數,但空可以作爲傳遞在我的例子中。

5

使用Dot net core 2.0 AuthorizationService.AuthorizeAsync不再返回布爾值,它會返回一個AuthorizationResult。對於點網核心2.0工作版本將是這樣的:

@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> 
} 
-1

如果你打算在許多視圖利用這一點,那麼你最好實現自定義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; 
    } 
} 

然後打開_ViewImports.cshtml並添加下一個指令:

@inherits MyRazorPage<TModel> 

現在你可以CAL升HasPolicyAsync()從任何觀點方法:

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

它看起來更加簡潔。

相關問題