asp.net-mvc - .NET Core 自定义授权过滤器
问题描述
我正在 MVC .NET Core 2 中开发一个新应用程序,但我必须使用在 MVC5 中开发的另一个应用程序中使用的现有身份验证和授权。它使用当前用户详细信息调用 Web 服务以获取用户所在的组和角色的列表,这是在 GetUserRoles 方法中完成的。从谷歌搜索来看,与 MVC 5 相比,现在的做法似乎有所不同。谁能帮我实现它,这样我就可以像这样使用它:
[BasicAuthorisation(Roles = "SpecificUser")]
这是我尝试在 .NET Core 中实现的过滤器片段:
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class BasicAuthorisation : AuthorizeAttribute, IAuthorizationFilter
{
MemoryCache mc = MemoryCache.Default;
private ClaimsPrincipal _principal;
private string _applicationName = "";
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool skipAuthorisation = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
_principal = HttpContext.Current.User as ClaimsPrincipal;
if (_principal.Identity == null)
{
_principal = Thread.CurrentPrincipal as ClaimsPrincipal;
}
_applicationName = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"];
if (_principal.Identity.IsAuthenticated)
{
if (!skipAuthorisation)
{
// set userRole cache name
string userRoleCache = _principal.Identity.Name.Replace(DoubleSlash, string.Empty) + CacheSuffix;
List<string> userRoles = GetUserRoles(_principal, userRoleCache);
//get system defined Role groups
List<string> restrictedRoleGroups = Roles.Split(_doubleBar, StringSplitOptions.RemoveEmptyEntries).Select(r => r.Trim()).ToList();
// iterate groups for authorisation
for (int i = 0; i < restrictedRoleGroups.Count(); i++)
{
List<string> restrictedRoles = restrictedRoleGroups[i].Split(',').Select(r => r.Trim()).ToList();
List<string> matchingRoles = (from ur in userRoles
where (restrictedRoles.Any(mr => ur == mr))
select ur).ToList();
if (matchingRoles.Count().Equals(restrictedRoles.Count()))
{
_outcome = true;
}
}
}
else { _outcome = true; }
}
if (_outcome == false)
{
filterContext.Result = new RedirectResult("~/Message/Index");
}
}
解决方案
推荐阅读
- c# - 如何使用 Youtube API V3 在 C# 中获取我的订阅者列表?
- r - 用一个字符分割一个 sf 对象而不删除它在 R 中的几何图形
- javascript - 无法使用 React js 从本地文件夹显示 svg
- r - 如何使用 ggparliament 获得显示每个政党所需颜色的图形?
- powershell - Powershell Construct Date ForEach 多次返回第一个文件的日期
- php - Laravel 应用程序不保存数据且不显示任何错误
- python-3.x - self 指的是超类而不是子类
- r - 如何删除出现不同 NA 的观察行
- python - 遍历文件夹中的所有 txt 文件时出现 Unicode 解码错误
- javascript - Vue watch 意外调用了两次