Custom Authentication in ASP.Net-Core

后端 未结 4 1202
暖寄归人
暖寄归人 2020-11-28 19:26

I am working on a web app that needs to integrate with an existing user database. I would still like to use the [Authorize] attributes, but I don\'t want to use

4条回答
  •  情深已故
    2020-11-28 19:53

    I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:

    First of all, you should change signature of SignIn method in UserManager class from:

    public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    

    to:

    public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    

    It's because you should never use async void, especially if you work with HttpContext. Source: Microsoft Docs

    The last, but not least, your Configure() method in Startup.cs should contains app.UseAuthorization and app.UseAuthentication in proper order:

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    

提交回复
热议问题