如何使用 OpenIdConnect 身份验证登录 ASP.NET 核心身份用户



我正在使用 ASP.NET 标识对我的用户进行身份验证,我也希望能够通过Azure AD执行此操作。所有用户都将事先进入数据库,因此,如果 AzureAD 登录成功,我需要做的就是登录他们并设置 cookie。问题是,当我实施新的外部身份验证并验证它们是否存在于我的数据库中时,它们未登录。因此,在成功远程登录后,如果我在我的控制器中检查User.Identity.IsAuthenticated它返回true,但_signInManager.IsSignedIn(User),它会返回false。我试图遵循 MS 指南和文档,但我认为我的配置有问题。

这是启动:

services.AddMvc(options => options.EnableEndpointRouting = false)
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddRouting(options =>
{
    options.LowercaseQueryStrings = true;
    options.LowercaseUrls = true;
});
services.Configure<CookiePolicyOptions>(options =>
{
    options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("<my_db_connection_string_here>")));
services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddUserManager<UserManager<ApplicationUser>>();
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    Configuration.GetSection("OpenIdConnect").Bind(options);
    options.TokenValidationParameters.ValidateIssuer = false;
    options.Events = new OpenIdConnectEvents
    {
        OnAuthorizationCodeReceived = async ctx =>
        {
            var request = ctx.HttpContext.Request;
            var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);
            var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
            string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var authContext = new AuthenticationContext(ctx.Options.Authority);
            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource);
            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
    };
});
var builder = services.AddIdentityCore<ApplicationUser>(options =>
{
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 6;
    options.Password.RequireLowercase = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;
    options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddLogging(options =>
{
    options.AddConfiguration(Configuration.GetSection("Logging"))
        .AddConsole();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        IdentityModelEventSource.ShowPII = true;
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    var builder = new ConfigurationBuilder()
       .SetBasePath(env.ContentRootPath)
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
       .AddEnvironmentVariables();
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

在我的控制器中:

[AllowAnonymous]
public IActionResult AzureLogin()
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction(nameof(HandleLogin)):
    }
     return Challenge(new AuthenticationProperties
     {
         RedirectUri = Url.Action(nameof(HandleLogin))
     });
}
[Authorize]
public async Task<IActionResult> HandleLogin()
{
    var isAuth = User.Identity.IsAuthenticated; // true
    var isSigned = _signInmanager.IsSignedIn(User); // false
    return ....
}

您可以尝试将 cookie 设置为 AutomaticAuthenticate true

services.Configure<IdentityOptions>(options => { 
    // other configs
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
});

以下是我设法做到的:由于我通过 ASP.NET 身份授权用户,因此我将身份验证选项中的默认身份验证方法更改为options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;,并且在OpenIdConnectOptions OnAuthorizationCodeRecieved事件中,我通过SignInManager.SignInAsync()方法验证并登录身份用户

相关内容

  • 没有找到相关文章

最新更新