.net - 如何手动设置为未经授权并重定向到自定义页面?
问题描述
我正在向 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" });
});
}
有谁知道如何根据令牌信息为未经授权的用户实现重定向?
解决方案
通过添加基于令牌组的角色来修复它。将此添加到 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");
}
}
推荐阅读
- reactjs - 如何修复 React 应用程序中 Angular Web 组件的 CSS 问题?
- pine-script - 如何使用 pine 代码在交易视图上显示背景水印
- vue.js - 如何在 vue 的故事书中显示材料设计图标
- javascript - React/Redux 点击时激活多个组件
- java - Spring批处理不通过JPA将值插入数据库
- ios - 如何在我的 firebase 项目中访问不同的实时数据库?
- kubernetes - 在 k8s 中使用 AppRole 身份验证的 Vault 抛出 403
- c# - 如何在此处仅包含具有某些属性值的问题值?
- c++ - 如何升级到 C++17?
- c# - 是否有用于将 C# 模型的更改转换为 SQL 语句的库?