簡體   English   中英

使用 ASP.NET MVC 4 中的特定方案進行授權

[英]Authorize with a specific scheme in ASP.NET MVC 4

在 asp.net MVC 4 中的 Controller 上使用[Authorize]屬性時,有沒有辦法要求特定的授權方案

我期待這樣的事情(順便說一句,這在.net 核心中是完全可能的)

[Authorize(AuthenticationSchemes = "Bearer")]
public class MyController : Controller { }

據我所知,沒有什么開箱即用的東西可以讓你寫這個。
標准授權屬性不支持這一點。

但是您可以編寫自己的屬性並檢查傳入的身份聲明。我使用了 ASP.NET 核心授權策略的反向移植到 .NET 完整框架: httpsgithub://or.com/寫這樣的規則。

如何檢查你來自哪個令牌? 通常你會看到類似於 "idp": "oidc" 的聲明

如何獲得索賠? ((ClaimsPrinciple)User).Claims(在 Controller 代碼中)

正如@Chetan Ranpariya 在評論中所建議的那樣,我最終實現了一個派生屬性(來自AuthorizeAttribute )。 根據文檔,覆蓋AuthroizeCore方法是這樣做的方法。

當被覆蓋時,為自定義授權檢查提供一個入口點。

這是一個工作示例以供將來參考

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public string AuthSchemes { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (this.AuthSchemes != null)
        {
            string scheme = httpContext?.User?.Identity?.AuthenticationType;
            if (string.IsNullOrWhiteSpace(scheme))
            {
                return false;
            }

            return this.AuthSchemes.Split(',').Contains(scheme);
        }

        return base.AuthorizeCore(httpContext);
    }
}

屬性可以這樣使用

[MyAuthorize(AuthSchemes = CookieAuthenticationDefaults.AuthenticationType)]
public class MyController : Controller { }

暫無
暫無

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

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