使用 ASP.NET MVC 4 中的特定方案授权
Authorize with a specific scheme in ASP.NET MVC 4
在 asp.net MVC 4 中使用控制器上的 [Authorize]
属性时,有没有办法要求特定的 授权方案?
我期待这样的事情(这在 .net core 顺便说一句是完全可能的)
[Authorize(AuthenticationSchemes = "Bearer")]
public class MyController : Controller { }
据我所知,没有现成的东西可以让你写这个。
标准授权属性不支持此功能。
但是您可以编写自己的属性并检查传入的身份声明。
我使用 ASP.NET 核心授权策略向后移植到 .NET 完整框架:https://github.com/DavidParks8/Owin-Authorization 来编写此类规则。
如何查看你来自哪个token?
通常您会看到类似于 "idp" 的声明:"oidc"
如何获得理赔? ((ClaimsPrinciple)User).Claims(控制器代码中)
正如@Chetan Ranpariya 在评论中所建议的那样,我最终实现了一个派生属性(来自 AuthorizeAttribute
)。根据 documentation,覆盖 AuthroizeCore
方法是这样做的方法。
When overridden, provides an entry point for custom authorization checks.
这是一个工作示例以供将来参考
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 { }
在 asp.net MVC 4 中使用控制器上的 [Authorize]
属性时,有没有办法要求特定的 授权方案?
我期待这样的事情(这在 .net core 顺便说一句是完全可能的)
[Authorize(AuthenticationSchemes = "Bearer")]
public class MyController : Controller { }
据我所知,没有现成的东西可以让你写这个。
标准授权属性不支持此功能。
但是您可以编写自己的属性并检查传入的身份声明。 我使用 ASP.NET 核心授权策略向后移植到 .NET 完整框架:https://github.com/DavidParks8/Owin-Authorization 来编写此类规则。
如何查看你来自哪个token? 通常您会看到类似于 "idp" 的声明:"oidc"
如何获得理赔? ((ClaimsPrinciple)User).Claims(控制器代码中)
正如@Chetan Ranpariya 在评论中所建议的那样,我最终实现了一个派生属性(来自 AuthorizeAttribute
)。根据 documentation,覆盖 AuthroizeCore
方法是这样做的方法。
When overridden, provides an entry point for custom authorization checks.
这是一个工作示例以供将来参考
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 { }