使用HttpContext.SignInAsync实现简单的授权

1. 将认证添加到服务中

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                //登入地址
                options.LoginPath = "/Account/FcbLogin/";
                //登出地址
                options.LogoutPath = "/Account/FcbLogout/";
                //设置cookie过期时长
                //options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            });

所有CookieAuthenticationOptions 属性可以查看微软官方文档
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 注入管道

这里认证要在授权之前注入

app.UseAuthentication();

3. 添加登入和登出

这里我没有验证用户账号密码,只是写了登入和登出的相关代码,这里也可以喝注入认证那里一样,这是票证过期时间

[HttpPost]
public async Task<ActionResult> Login(UserLogin model)
{
    //这里的scheme一定要和注入服务的scheme一样
    var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
    //自定义的claim信息
    identity.AddClaim(new Claim("abc", "123"));
    AuthenticationProperties properties = new AuthenticationProperties()
    {
        //设置cookie票证的过期时间
        ExpiresUtc = DateTime.Now.AddDays(1),
        RedirectUri = model.ReturnUrl
    };
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);
 
    if (string.IsNullOrEmpty(model.ReturnUrl))
    {
        return LocalRedirect("/");
    }
    return LocalRedirect(model.ReturnUrl);
}  
[HttpGet]
public ActionResult FcbLoginOut()
{
    //AuthenticationProperties properties = new AuthenticationProperties()
    //{
    //    ExpiresUtc = DateTime.Now.AddDays(-100)
    //};
    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Ok();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值