码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-05-08 17:38:15      阅读:934      评论:0      收藏:0      [点我收藏+]

标签:actor   return   serve   cookies   factory   gui   ide   nas   only   

注入:

    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]

例:

技术分享图片

技术分享图片

 

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

标签:actor   return   serve   cookies   factory   gui   ide   nas   only   

原文地址:https://www.cnblogs.com/Cein/p/9009284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!