简体   繁体   English

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

[英]How to sign in ASP.NET Core Identity User, using OpenIdConnect Authentication?

I'm using ASP.NET Identity to authenticate my users and I want to be able to do this via Azure AD as well. 我正在使用ASP.NET Identity来验证我的用户,我也希望能够通过Azure AD进行身份验证。 All users will be in the DB beforehand, so all I need to do is sign them in and set their cookies, if the AzureAD login was successful. 所有用户都将事先位于数据库中,因此,如果AzureAD登录成功,那么我需要做的就是登录他们并设置其Cookie。 The problem is that when I implement the new external authentication and validate that they exist in my DB, they are not signed in. So after successful remote login, if in my controller I check for User.Identity.IsAuthenticated it returns true , but _signInManager.IsSignedIn(User) , it returns false . 问题是,当我实施新的外部身份验证并验证它们是否存在于数据库中时,它们没有登录。因此,在成功远程登录之后,如果在我的控制器中检查User.Identity.IsAuthenticated它返回true ,但是_signInManager.IsSignedIn(User) ,它返回false I have tried to follow the MS guidelines and documentation, but I assume there is something wrong with my config. 我试图遵循MS指南和文档,但是我认为我的配置有问题。

Here's the startup: 这是启动:

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?}");
    });

And in my controller: 在我的控制器中:

[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 ....
}

You could try to set AutomaticAuthenticate cookie to true : 您可以尝试将AutomaticAuthenticate cookie设置为true

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

Here's how I managed to do it: Since I'm authorizing the user via ASP.NET Identity, I changed the default authentication method in the authentication options to options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; 我设法做到这一点:因为我通过ASP.NET Identity授权用户,所以我将身份验证选项中的默认身份验证方法更改为options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; and in the OpenIdConnectOptions OnAuthorizationCodeRecieved event, I validate and sign in the Identity User via the SignInManager.SignInAsync() method OpenIdConnectOptions OnAuthorizationCodeRecieved事件中,我通过SignInManager.SignInAsync()方法验证并登录身份用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使 Asp.Net Core Identity 与 OpenIdConnect 一起工作 - How to make Asp.Net Core Identity to work with OpenIdConnect 如何在 ASP.NET Core Identity 中注销其他用户 - How to sign out other user in ASP.NET Core Identity 如何在ASP.NET Core Identity中注销用户 - How to sign out a user in ASP.NET Core Identity 不能在asp.net core 2.0中使用CookieAuthenticaton和openidConnect身份验证 - Cannot use CookieAuthenticaton and openidConnect Authentication in asp.net core 2.0 使用ASP.NET Core身份验证和基于令牌的身份验证时,为什么要登录新用户? - Why sign-in a new user when using ASP.NET Core Identity and token-based auth? 为什么 ASP.NET Core MVC 3.1 项目不允许我使用 Identity 使用注册用户登录 - Why ASP.NET Core MVC 3.1 project wont let me sign in with a register user using Identity ASP.NET Core 5 OpenIdConnect认证cookies在理论上是如何工作的? - How do the ASP.NET Core 5 OpenIdConnect authentication cookies work in theory? 使用Firebase和Identity的ASP.NET Core API身份验证 - ASP.NET Core API authentication using Firebase and Identity 有没有办法使用 Windows 身份验证注销并以其他用户身份登录? [ASP.NET Core 3.1 MVC] - Is there a way to sign out and login as another user using Windows authentication? [ASP.NET Core 3.1 MVC] 将 ASP.NET Core 标识与 IdentityServer4 结合使用 - 身份验证 - Using ASP.NET Core Identity with IdentityServer4 - Authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM