Dotnet
该示例展示cookie登入登出的相关代码
Startup.cs 配置
public void ConfigureServices(IServiceCollection services)
{
...
// 添加cookie认证
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(m =>
{
m.LoginPath = "/member/login";
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<SenparcWeixinSetting> senparcWeixinSetting, IOptions<SenparcSetting> senparcSetting)
{
...
// 注意这里,在UseAuthorization之前添加UseAuthentication
app.UseAuthentication();
app.UseAuthorization();
}
MemberController.cs
[AllowAnonymous]
public IActionResult Login([FromBody] loginArgsModel)
{
...
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.username, ClaimValueTypes.String, null),
};
var userIdentity = new ClaimsIdentity("Form");
userIdentity.AddClaims(claims);
var principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return Redirect("");
}
public IActionResult Logout(string returnUrl)
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (string.IsNullOrEmpty(returnUrl) || returnUrl == "/member/logout") returnUrl = "/member";
return Redirect(returnUrl);
}
坑1:使用oauth2.0的方式做的单点登录,将SignOutAsync包装成接口给客户端调用,发现无效
原因是使用的cookie验证,客户端调用时,并没有带上cookie,自然就没效,解决办法是从客户端直接跳到单点登录的logout页面
这个时候,浏览器会带上cookie,实现cookie的退出