在Intranet Web应用程序中使用Windows身份验证我想实现以下目标:
在我搜索答案时,建议我需要将ClaimsTransformation
添加到我的应用程序中:
How do I use Windows Authentication with users in database
Populate custom claim from SQL with Windows Authenticated app in .Net Core
Caching Claims in .net core 2.0
虽然我不完全理解解决方案以及为什么ClaimsTransformation
在每个请求中都会发生,所以我正在寻找以下答案:
ClaimsTransformation
需要ASP.NET核心身份吗?ClaimsTransformation
吗?答案 0 :(得分:1)
这article给了我一些想法,这是一个可能的解决方案。
控制器将从具有需要Authenticated
声明的策略的基本控制器继承。当它不存在时,它将转到AccessDeniedPath
并静默执行登录,并添加Authenticated
声明以及任何其他声明,如果已存在,则会显示“拒绝访问”消息。< / p>
创建新的ClaimsIdentity
时,由于收到HTTP 400 - Bad Request (Request Header too long)错误消息,我必须删除原始身份中的大多数声明。
这种方法有什么明显的问题吗?
<强> Startup.cs 强>
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Home/Login";
options.AccessDeniedPath = "/Home/AccessDenied";
});
services.AddAuthorization(options =>
{
options.AddPolicy("Authenticated",
policy => policy.RequireClaim("Authenticated"));
options.AddPolicy("Admin",
policy => policy.RequireClaim("Admin"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
<强>控制器强>
[Authorize(Policy = "Authenticated")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize(Policy = "Admin")]
public IActionResult About()
{
return View();
}
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl)
{
var identity = ((ClaimsIdentity)HttpContext.User.Identity);
var claims = new List<Claim>
{
new Claim("Authenticated", "True"),
new Claim(ClaimTypes.Name,
identity.FindFirst(c => c.Type == ClaimTypes.Name).Value),
new Claim(ClaimTypes.PrimarySid,
identity.FindFirst(c => c.Type == ClaimTypes.PrimarySid).Value)
};
var claimsIdentity = new ClaimsIdentity(
claims,
identity.AuthenticationType,
identity.NameClaimType,
identity.RoleClaimType);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
new AuthenticationProperties());
return Redirect(returnUrl);
}
[AllowAnonymous]
public IActionResult AccessDenied(string returnUrl)
{
if (User.FindFirst("Authenticated") == null)
return RedirectToAction("Login", new { returnUrl });
return View();
}
}