具有Windows身份验证的ASP.NET Core身份

时间:2019-07-03 19:52:23

标签: c# asp.net-core windows-authentication asp.net-core-identity

我正在使用.NET Core 3.0 Preview6。
我们有一个启用了Windows身份验证的Intranet应用程序,这意味着只有有效的AD用户才能使用该应用程序。
但是,我们希望使用ASP.NET Identity运行我们自己的身份验证后端,因为它可以“开箱即用”地工作。我刚刚使用用户的Windows登录名向AspNetUsers表添加了一个列。

我要完成的是Windows用户使用Windows登录名自动登录到应用程序。
我已经创建了自定义身份验证中间件,请参见下面的代码:

public class AutoLoginMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public AutoLoginMiddleware(RequestDelegate next, ILogger<AutoLoginMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context, UserService userService, UserManager<IntranetUser> userManager, 
        SignInManager<IntranetUser> signInManager)
    {
        if (signInManager.IsSignedIn(context.User))
        {
            _logger.LogInformation("User already signed in");
        }
        else
        {
            if (context.User.Identity as WindowsIdentity != null)
            {
                _logger.LogInformation($"User with Windows Login {context.User.Identity.Name} needs to sign in");
                var windowsLogin = context.User.Identity.Name;


                var user = await userManager.Users.FirstOrDefaultAsync(u => u.NormalizedWindowsLogin == windowsLogin.ToUpperInvariant());

                if (user != null)
                {
                    await signInManager.SignInAsync(user, true, "automatic");
                    _logger.LogInformation($"User with id {user.Id}, name {user.UserName} successfully signed in");

                    // Workaround
                    context.Items["IntranetUser"] = user;
                }
                else
                {
                    _logger.LogInformation($"User cannot be found in identity store.");
                    throw new System.InvalidOperationException($"user not found.");
                }
            }
        }

        // Pass the request to the next middleware
        await _next(context);
    }
}

医生说SignInManager.SignInAsync创建了一个新的ClaimsIdentity-但似乎从未发生过-HttpContext.User始终是WindowsIdentity。在用户再次登录的每个请求中,对signInManager.IsSignedIn()的调用始终返回false。

我现在的问题是:以这种方式进行自动身份验证通常是一个好主意吗?存在哪些其他方式?

我的下一个要求是拥有一个自定义AuthorizationHandler。 这里的问题是,有时在HandleRequirementAsync方法中,AuthorizationHandlerContext.User.IdentityWindowsIdentity,然后对context.User.Identity.Name的调用会引发以下异常:

System.ObjectDisposedException: Safe handle has been closed.

Object name: 'SafeHandle'.

   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)

   at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)

   at Interop.Advapi32.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)

   at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, Boolean nullOnInvalidParam)

   at System.Security.Principal.WindowsIdentity.get_User()

   at System.Security.Principal.WindowsIdentity.<GetName>b__51_0()

   at System.Security.Principal.WindowsIdentity.<>c__DisplayClass67_0.<RunImpersonatedInternal>b__0(Object <p0>)

   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

我现在的假设是这两个部分不能很好地协同工作。有时似乎存在计时问题-在调用AuthorizationHandler

之间调用了我的自定义AutoLoginMiddleware

1 个答案:

答案 0 :(得分:1)

现在已解决。这是预览版本中的一个错误。现在它正在按预期工作。祝好运!

更新:我想发布.NET Core 3.1 Final的工作代码。

  1. Configure的框架中间件之后注册自定义登录中间件是必不可少的:
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseMiddleware<AutoLoginMiddleware>();
  1. 在自定义中间件中,登录用户后,您必须调用CreateUserPrincipalAsync并将此主体保存到HttpContext.User属性中。

    await signInManager.SignInAsync(user, true);
    context.User = await signInManager.CreateUserPrincipalAsync(user);
    
  2. 对于Blazor,我们必须使用AuthenticationStateProvider。它具有属性User,其中包含来自ClaimsPrincipal的{​​{1}}。就是这样。

  3. 您现在可以按照以下方式获取身份用户:

    HttpContext