【问题标题】:AspNetCore 2.2 as API - How to logout using Identity methods?AspNetCore 2.2 as API - 如何使用身份方法注销?
【发布时间】:2020-01-13 07:42:53
【问题描述】:

我使用 Angular 7 创建了 Web 应用程序 front-end, DotNetCore 2.2 为 back-end API(用于 db 的 SQL Server)。 最初创建项目时,我没有添加Authentication,因为 不需要 UI 页面。我计划将身份验证与 cookie 一起使用。

虽然 Login 和 [Authorize] 运行良好,但 Logout 不适用于 signInManager.SignOutAsync()。

微软声明: “SignOutAsync 清除存储在 cookie 中的用户声明。 调用 SignOutAsync 后不要重定向,否则用户将不会退出。” 似乎 cookie 没有被删除,并且被 API 接受为有效(除非它过期)。 我尝试使用 Response.Cookies.Delete() 和 HttpContext.SignOutAsync() 没有成功。

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CORS", builder => 
        {
            builder.WithOrigins("http://localhost:42000")
            .AllowAnyHeader()
            .AllowCredentials();
        });
    });

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => false;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<NGDbContext>(options =>  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<NGUser, IdentityRole>()
            .AddEntityFrameworkStores<NGDbContext>()
            .AddDefaultTokenProviders();

    services.Configure<IdentityOptions>(options =>
    {
        // some options...
    });

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.SlidingExpiration = true;
        //options.CookieName = "MyCookie";
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddScoped<NamesService, NamesService>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();

        InitialSeeder.Seed(app);
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors("CORS");
    app.UseHttpsRedirection();
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseMvc();
}
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private UserManager<NGUser> userManager;
    private SignInManager<NGUser> signInManager;

    public AuthController(UserManager<NGUser> userManager, SignInManager<NGUser> signInManager)
    {
        this.userManager = userManager;
        this.signInManager = signInManager;
    }

    [HttpPost("Login")]
    public async Task<ActionResult> Login(LoginModel model)
    {
        var user = await this.userManager.FindByNameAsync(model.Username);

        if (user == null)
        {
            return Unauthorized();
        }

        var signInResult = await this.signInManager.PasswordSignInAsync(user, model.Password, false, false);

        if (!signInResult.Succeeded)
        {
            return Unauthorized();
        }

        return Ok();
    }

    [HttpPost("Logout")]
    public async Task<ActionResult> Logout()
    {
        await this.signInManager.SignOutAsync();

        return Ok();
    }
}

是否可以从身份登录注销方法中受益? 还是应该使用自定义方法?

【问题讨论】:

标签: asp.net-core asp.net-identity


【解决方案1】:

为了成功注销 signInManager.SignOutAsync() 只需要一个 cookie。
我没有提供 Angular HttpClient.post() 方法 - 我错过了 null 作为第二个参数。
工作角面:

login(model: LoginModel){

    return this.http.post("https://localhost:50000/api/auth/login", model, { withCredentials: true });
  }

 logout(){

    return this.http.post("https://localhost:50000/api/auth/logout", null, { withCredentials: true });
  }

工作 .Net 端:
两种注销方法都有效:

  • this.HttpContext.Response.Cookies.Delete(".AspNetCore.Identity.Application");
  • 等待这个.signInManager.SignOutAsync();

第一个只删除选定的cookie,而第二个删除三个.AspNetCore.Identity.ApplicationIdentity.ExternalIdentity.TwoFactorUserId
SignOutAsync 调用三个方法:
await Context.SignOutAsync(IdentityConstants.ApplicationScheme);
await Context.SignOutAsync(IdentityConstants.ExternalScheme);
await Context.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);

是的,可以在 API 中使用 Identity。

【讨论】:

    猜你喜欢
    • 2018-07-31
    • 2021-10-23
    • 2016-11-07
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多