处理未经授权的OpenID连接策略?

时间:2019-07-05 18:40:46

标签: asp.net-core azure-active-directory

我正在关注此维基Quickstart: Add sign-in with Microsoft to an ASP.NET Core web app

我有这样的政策:

services.AddAuthorization(options =>
{
    options.AddPolicy("CanAccessAdminGroup",
        policyBuilder => policyBuilder.RequireClaim("groups", "Guid"));
});

我的控制器装饰有[Authorize(Policy = "CanAccessAdminGroup")]

当用户在此AAD组中时,哪个可以正常工作。 但是当用户不在组中时,我会被发送到xxx/Account/AccessDenied?returnurl=xx

如何更改重定向以使用其他控制器/操作,例如/identity/index

我试图做到这一点,但是没有起作用:

OnAuthenticationFailed = context =>
{
    context.Response.Redirect("Identity/Index");
    context.HandleResponse(); // Suppress the exception
    return Task.CompletedTask;

这是“调试”窗口的输出:

  

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:过滤器“ Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”上的请求授权失败。   Microsoft.AspNetCore.Mvc.ForbidResult:Information:使用身份验证方案()执行ForbidResult。   Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:信息:AuthenticationScheme:AzureADCookie被禁止。

1 个答案:

答案 0 :(得分:1)

您可以首先创建一个授权要求:

public class MatchGroupRequirement : IAuthorizationRequirement
{
    public String  GroupID { get; }

    public MatchGroupRequirement(string groupID)
    {
        GroupID = groupID;
    }
}

创建一个负责处理需求属性评估的授权处理程序,在自定义授权中,您可以使用AuthorizationFilterContextRedirectToActionResult重定向到任何所需的控制器操作:

public class MatchGroupHandler : AuthorizationHandler<MatchGroupRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                    MatchGroupRequirement requirement)
    {
        var redirectContext = context.Resource as AuthorizationFilterContext;
        var groups = context.User.Claims.Where(c => c.Type == "groups").ToList();
            var matchingvalues = groups.Where(stringToCheck => stringToCheck.Value.Contains(requirement.GroupID)).FirstOrDefault();
        //check the condition 
        if (matchingvalues == null)
        {
            redirectContext.Result = new RedirectToActionResult("identity", "index", null);
            context.Succeed(requirement);
            return Task.CompletedTask;
        }
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

政策和处理程序注册:

services.AddAuthorization(options =>
{
    options.AddPolicy("MatchGroup", policy =>
        policy.Requirements.Add(new MatchGroupRequirement("ddf1ad17-5052-46ba-944a-7da1d51470b0")));
});

services.AddSingleton<IAuthorizationHandler, MatchGroupHandler>();

将策略应用于MVC控制器/操作:

[Authorize(Policy = "MatchGroup")]
public IActionResult Contact()
{
    ViewData["Message"] = "Your contact page.";

    return View();
}