我正在开发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");
}
}