在asp.net core mvc中提供了權限驗證框架,前面的文章中已經介紹了如何進行權限控制配置,權限配置好后,權限驗證邏輯自動就會執行,但是在某些情況下,我們可能需要在代碼里或者視圖中通過手工方式判斷權限,我們現在就來介紹下具體的操作方法。
如果在控制器方法里想要判斷當前用戶是否具有某個權限,可以直接使用HttpContext.User.HasClaim(string cliamtype,string cliamvalue)方法進行判斷,該方法返回bool類型,返回true表示具有權限,否則不具有。
在視圖上我們往往需要控制某個按鈕或者超鏈接的權限,具有權限按鈕就顯示,否則不現實。那怎么樣才能達到這樣的效果?方法介紹如下:
1,在視圖中直接使用HttpContext.User.HasClaim(string cliamtype,string cliamvalue)判斷權限,然后控制按鈕是否顯示
1
2
3
4
|
@ if (HttpContext.User.HasClaim( "User" , "Delete" )) { <input type= 'button' value= "刪除" /> } |
上面的代碼寫在視圖中,表示如果具有用戶的刪除權限,就顯示刪除按鈕。這種方式比如在所有需要驗證的地方,都按照這樣的格式去書寫。
2,借助于asp.net core mvc的新特性taghelper可以簡化第一種方式,至于什么是taghelper,以及它的作用這里就不再介紹,大家可以百度或谷歌搜索,這里直接介紹如何自定義權限驗證的taghelper。
1
|
< a asp-claim = "goods,edit" asp-action = "addgoods" asp-route-id = "@goods.Id" class = "btn-icon " title = "編輯" >< i class = "icon-common-edit icon-pencil" ></ i ></ a > |
上面的代碼是我們最終的效果,表示這個超鏈接是有在用戶具有claim(type=goods,value=edit)權限的時候才顯示,下面我們就來介紹如何實現這個taghelper。
1)首先我們定義一個類,派生自TagHelper類,并增加claim屬性定義,并增加ViewContext
1
2
3
4
5
6
7
8
9
|
class ClaimTagHelper:TagHelper { private const string ClaimAttributeName = "asp-claim" ; public ClaimTagHelper() { } [HtmlAttributeName(ClaimAttributeName)] public string Claim { get ; set ; } } |
2)我們的權限控制taghelper只運用于button,a,input的元素上,所有我們需要加上HtmlTargetElement的特性,代碼如下:
1
2
3
4
5
6
7
|
[HtmlTargetElement( "a" , Attributes = ClaimAttributeName)] [HtmlTargetElement( "button" , Attributes = ClaimAttributeName)] [HtmlTargetElement( "input" , Attributes = ClaimAttributeName, TagStructure = TagStructure.WithoutEndTag)] public class ClaimTagHelper: TagHelper { ...... } |
3)重寫TagHelper的Process方法,在方法中使用HttpContext.User.HasClaim進行權限判斷。在視圖中訪問HttpContext必須借助于ViewContext對象,所以我們需要在當前的TagHelper類中增加ViewContext引用,具體代碼如下:
1
2
3
4
5
6
7
8
9
|
public class ClaimTagHelper: TagHelper { ..... [HtmlAttributeNotBound] [ViewContext] public ViewContext ViewContext { get ; set ; } ..... } |
基本條件都具備了,然后就是Process實現,直接上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public override void Process(TagHelperContext context, TagHelperOutput output) { if ( string .IsNullOrEmpty(Claim)) { return ; } string [] claimData = Claim.Split( new char [] { '-' }, StringSplitOptions.RemoveEmptyEntries); if (claimData.Length == 1) { if (!ViewContext.HttpContext.User.HasClaim(m => m.Type == claimData[0])) { //無權限 output.SuppressOutput(); } } else { if (!ViewContext.HttpContext.User.HasClaim(m => m.Type == claimData[0] && m.Value == claimData[1])) { //無權限 output.SuppressOutput(); } } } |
到這里就介紹完了,謝謝大家,如有不足之處,歡迎大家指導。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!