.net core使用官方CookieAuthentication身份验证

注入:

复制代码
复制代码
    public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //services.AddJwtAuthorization(Configuration);

            var types = new[] { typeof(ApplicationModule) };
            services.AddScoped<IIdentityManager, IdentityManager>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                                .AddCookie(options =>
                                {
                                    options.LoginPath = new PathString("/login/index");
                                    options.AccessDeniedPath = new PathString("/Error/index");
                                });

            services.AddMvc();


            var iservice = services.AddFramework<LiveFactoryDbContext>(opt =>
              {
                  opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
              }, types, types);
          
            return iservice;
        }
复制代码
复制代码

新建对应类

复制代码
复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Linq;

namespace LiveFactory.Core
{
    public interface IIdentityManager
    {
        ClaimsIdentity CreateIdentity(IdentityUser user);
        Task SignInAsync(IdentityUser user);
        Task SignOutAsync();
    }
    public class IdentityManager : IIdentityManager
    {
        IHttpContextAccessor _contextAccessor;
        public IdentityManager(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        public virtual ClaimsIdentity CreateIdentity(IdentityUser user)
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.PrimarySid, user.Id));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            return identity;
        }

        public virtual async Task SignInAsync(IdentityUser user)
        {
            await _contextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(CreateIdentity(user)));
        }

        public virtual async Task SignOutAsync()
        {
            await _contextAccessor.HttpContext.SignOutAsync();
        }
    }


}
复制代码
复制代码

 

登录注销

复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LiveFactory.Application;
using LiveFactory.Application.Base;
using LiveFactory.Core;
using Microsoft.AspNetCore.Mvc;
//using JFJT.Authorize.IJwtTokenManager;

namespace LiveFactory.Web.Controllers
{
    public class LoginController : Controller
    {
        public readonly IUserService _IUserService;
        public readonly IIdentityManager _identityManager;
        public LoginController(IUserService userService, IIdentityManager identityManager)
        {
            _IUserService = userService;
            _identityManager = identityManager;
        }
        public IActionResult Index()
        {
            return View();
        }

        public async Task<ResultDto<UserDto>> Login(UserDto loginModel)
        {
            var result = _IUserService.Login(loginModel);
            if (result.Success)
            {
                await _identityManager.SignInAsync(new Microsoft.AspNetCore.Identity.IdentityUser() { Id = Guid.NewGuid().ToString(), PasswordHash = result.Data.Password.ToString(), UserName = result.Data.Account.ToString() });
            }
            return result;
        }
        
        public ActionResult LoginOut()
        {
            //_authenticationManager.SignOut();
            _identityManager.SignOutAsync();
            return RedirectToAction("Index");
        }
    }
}
复制代码
复制代码

 

需要验证的控制器中加入

 [Authorize]

例:

 

那是一座岛,岛上有青草,鲜花,美丽的走兽与飞鸟!

posted on   itjeff  阅读(118)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-06-30 关于JS下offsetLeft,style.left,以及jquery中的offset().left,css("left")的区别。
2015-06-30 jQuery - 基于serializeArray的serializeObject
2015-06-30 基于Js实现的UrlEncode和UrlDecode函数代码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示