首页 > 解决方案 > Asp.Net 3.1 使用 Windows 身份验证和角色授权

问题描述

使用 Asp.net 和 .Net Core 3.1 进行设置后,我使用带有角色的用户名/密码升级了以前的身份系统以使用 Windows 身份验证。我创建了一个 ClaimsTransformation,它获取 windows 身份并创建一个具有用户关联角色的新 ClaimsPrincipal。这部分正在工作我的 startup.cs 看起来像这样(删除了一些部分)

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddTransient<IClaimsTransformation, KiwaClaimsTransformation>();

     services.AddAuthentication(IISDefaults.AuthenticationScheme);

     services.AddAuthorization();

     ...
     services.AddControllers();

     services.AddControllersWithViews()
      .AddSessionStateTempDataProvider();
 }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
            ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
 {
       ...

       app.UseStaticFiles();

       app.UseCookiePolicy();

       app.UseRouting();

       app.UseAuthentication();

       app.UseAuthorization();

       app.UseEndpoints(endpoints =>
       {
           endpoints.MapControllers();
           endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
           // catch all for not found
           endpoints.MapControllerRoute("NotFound", "{*url}",
                    new {controller = "Error", action = "ResourceNotFound"});
       });

       ...
  }

ClaimsTransformation 看起来像这样

 public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var identity = (ClaimsIdentity)principal.Identity;
            if (identity == null) return principal;

            var userName = _config["LoginUserName"];
            if (userName == null)
            {
                userName = identity.Name;
                if (userName == null) return principal;
            }

            // need to go and build the Roles claims for the user based on the User Name as a lookup on User table 
            var claims = new List<Claim>
            {
                new Claim(@"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", userName, "Name")
            };
            claims.AddRange(_userLookup.GetUserRolesByNetworkId(userName)
                .Select(role => new Claim(ClaimTypes.Role, role)));

            //The claim identity uses a claim with the claim type below to determine the name property.
            // Get User Roles from database and add to list of claims.
            var newClaimsIdentity = new ClaimsIdentity(claims, "Kerberos", "", "http://schemas.microsoft.com/ws/2008/06/identity/claims/role");

            return new ClaimsPrincipal(new ClaimsPrincipal(newClaimsIdentity));
        }

我有一个看起来像这样的基本 HomeController

  public class HomeController : Controller
    {
        private readonly LoggedOnUser _loggedOnUser;

        public HomeController(LoggedOnUser loggedOnUser)
        {
            _loggedOnUser = loggedOnUser;
        }

        [Authorize]
        [HttpGet]
        public IActionResult Index()
        {
            // check and make sure the user is allowed in 
            if (!_loggedOnUser.IsValidKiwaUser)
            {
                return RedirectToActionPermanent("NotAuthorised");
            }
            return View();
        }

        [Authorize]
        public IActionResult OperationResults()
        {
            ViewBag.Title = (string)TempData["Title"];
            string jsonString = (string)TempData["OperationResults"];
            if (string.IsNullOrWhiteSpace(jsonString))
            {
                return RedirectToPage("/Error/NoResults");
            }
            return View(JsonConvert.DeserializeObject<List<OperationResult>>(jsonString));
        }


        public IActionResult NotAuthorised()
        {
            return View();
        }

所有控制器都具有 [Authorize(Role="...")],并且授权正在正确发生,并且角色通过 ClaimsTransformation 作为声明添加。 我遇到的问题是,如果我点击网站的根目录(调试这是https://localhost:44391),那么路由会将我发送到控制器上的 NotAuthorised 页面???它应该默认转到默认 Endpoint 中定义的https://localhost:44391/Home/index如果我输入https://localhost:44391/Home/index它可以工作并显示正确的主登录页面,但如果我不完整包含https://localhost:44391/Home/index则它会返回作为未经授权的。

我在这里错过了什么吗?我也可以转吗

标签: asp.net-mvcasp.net-identitywindows-authenticationasp.net-core-3.1asp.net-roles

解决方案


我最终发现了这个问题。在转换到 Windows 身份验证的过渡期间,我在产品中保留了 cookie 支持。但这所做的是将起始页面存储为 NotAuthorized 页面。清除 cookie(并随后从应用程序中删除 cookie 支持),修复了问题,并且角色一直被评估。因此,为什么我使用查找(内存缓存)来访问用户及其声明 - 因为它被所有用户请求调用

哦,顺便说一句。如果您以此为例,实际上不再需要检查 HomeController/Index 中的 _loggedOnUser.IsValidKiwaUser


推荐阅读