Как войти в ASP.NET Core Identity User, используя аутентификацию OpenIdConnect? - PullRequest
2 голосов
/ 03 июня 2019

Я использую ASP.NET Identity для аутентификации своих пользователей, и я хочу сделать это также через Azure AD. Все пользователи будут в БД заблаговременно, поэтому все, что мне нужно сделать, это войти в них и установить их куки, если вход в AzureAD был успешным. Проблема в том, что когда я внедряю новую внешнюю аутентификацию и проверяю, что они существуют в моей БД, они не входят в систему. Так что после успешного удаленного входа в систему, если в моем контроллере я проверяю 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 голосов
/ 04 июня 2019

Вот как мне удалось это сделать: Поскольку я авторизую пользователя через ASP.NET Identity, я изменил метод аутентификации по умолчанию в параметрах аутентификации на options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;, а в событии OpenIdConnectOptions OnAuthorizationCodeRecieved я проверяю и регистрирую пользователя Identity через * 1004. * метод

0 голосов
/ 04 июня 2019

Вы можете попробовать установить AutomaticAuthenticate cookie на true:

services.Configure<IdentityOptions>(options => { 
    // other configs
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...