.Net Core Identity外面使用Cookie中间件

本文介绍如何在ASP.NET Core应用中实现基于Cookie的身份验证流程,包括配置、登录、注销及用户身份验证状态检查。

1、在 app.UseMvc 前面加上app.UseCookieAuthentication

app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "IdeaCoreUser",
                LoginPath = new PathString("/Login/Login/"),
                AccessDeniedPath = new PathString("/Account/Forbidden/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieDomain=""
            });

 2、登录

var claims = new List<Claim> {
    new Claim("FullName", customer.Username,ClaimValueTypes.String),
    new Claim("Role", "注册用户",ClaimValueTypes.String),
};
var userIdentity = new ClaimsIdentity(claims, "Customer");
var userPrincipal = new ClaimsPrincipal(userIdentity);
HttpContext.Authentication.SignInAsync("IdeaCoreUser", userPrincipal,
    new AuthenticationProperties
    {
        ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
        IsPersistent = false,
        AllowRefresh = false
    });

 3、退出登录

HttpContext.Authentication.SignOutAsync("IdeaCoreUser");

 

4、判断是否已经登录

var bol =HttpContext.User.Identity.IsAuthenticated;

 

5、使用IIdentity拓展方法来获取存的值

    public static class IdentityExtension
    {
        public static string FullName(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("FullName");
            return (claim != null) ? claim.Value : string.Empty;
        }
        public static string Role(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("Role");
            return (claim != null) ? claim.Value : string.Empty;
        }
    }

 

var fullname = HttpContext.User.Identity.FullName();

 

转载于:https://www.cnblogs.com/ideacore/p/6282976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值