首页 > 解决方案 > 如何手动设置为未经授权并重定向到自定义页面?

问题描述

我正在向 Web 应用程序添加自定义未经授权的页面。基于特定的 AD 组,用户被允许登录,否则他们会被重定向到一个页面,该页面显示他们未经授权使用该应用程序。该组包含在令牌中,我想在 if 语句中过滤它。我尝试了以下选项,但都不起作用。

这是我的 startup.cs 文件(为简洁起见,删除了一些代码):

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie(options =>
        {
            options.SlidingExpiration = false;
            options.Cookie.Name = "mvcimplicit";

        })
    .AddOpenIdConnect("oidc", options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnTokenValidated = (TokenValidatedContext c) =>
            {
                var token = c.SecurityToken;
                var name = c.SecurityToken.Claims.FirstOrDefault(claim => claim.Type == "name");
                var group = c.SecurityToken.Claims.FirstOrDefault(claim => claim.Type == "group");
                if (name != null && group != null)
                {
                    if (!group.ToString().Contains("GROUP_ONE"))
                    {
                        // It hits these lines, but doesn't redirect
                        System.Diagnostics.Debug.WriteLine("Access denied!");
                        c.Response.StatusCode = 401;
                        c.HttpContext.Response.Redirect("~/Views/Shared/NoAccess.cshtml");
                    }
                }
                return Task.CompletedTask;
            }
        };
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // This doesn't redirect either
    app.UseStatusCodePages(context => {
        var request = context.HttpContext.Request;
        var response = context.HttpContext.Response;

        if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
        {
            response.Redirect("~/Views/Shared/NoAccess.cshtml");
        }

        return Task.CompletedTask;
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });
}

有谁知道如何根据令牌信息为未经授权的用户实现重定向?

标签: .net

解决方案


通过添加基于令牌组的角色来修复它。将此添加到 startup.cs:

options.Events = new OpenIdConnectEvents
{
    OnTokenValidated = (TokenValidatedContext c) =>
    {
        var token = c.SecurityToken;
        var name = c.SecurityToken.Claims.FirstOrDefault(claim => claim.Type == "name");
        var group = c.SecurityToken.Claims.FirstOrDefault(claim => claim.Type == "group");
        if (name != null && group != null)
        {
            // Only users present in this AD group are allowed access to the web app
            if (group.ToString().Contains("GROUP_ONE"))
            {
                var claimsIdentity = (ClaimsIdentity)c.Principal.Identity;
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            }
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Token NOT validated for user");
        }
        return Task.CompletedTask;
    }
};

然后根据这个 Role 处理 HomeController 中的重定向:

[Authorize]
public class HomeController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        // If user does not have the role of Admin, redirect to NoAccess page
        if (!User.IsInRole("Admin"))
        {
            return RedirectToAction("UnAuthorized");
        }

        return View();
    }

    public IActionResult UnAuthorized()
    {
        return View("~/Views/Shared/NoAccess.cshtml");
    }
}

推荐阅读