【问题标题】:Asp.Net 3.1 using Windows Authentication and Role AuthorisationAsp.Net 3.1 使用 Windows 身份验证和角色授权
【发布时间】:2020-04-17 09:14:03
【问题描述】:

使用 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 页面???它应该默认转到默认端点中定义的https://localhost:44391/Home/index。 如果我输入https://localhost:44391/Home/index,它会工作并显示正确的主登录页面,但如果我不完整地包含https://localhost:44391/Home/index,那么它会以未经授权的形式返回。

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

【问题讨论】:

  • 去掉 NotFound 控制器路由是否有效?只保留默认路由?

标签: asp.net-mvc asp.net-identity windows-authentication asp.net-core-3.1 asp.net-roles


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    相关资源
    最近更新 更多