如何使用OpenIdConnect身份验证登录ASP.NET Core身份用户?

时间:2019-06-03 19:19:38

标签: asp.net-core azure-active-directory asp.net-identity openid-connect oidc

我正在使用ASP.NET Identity来验证用户身份,我也希望能够通过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 ....
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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