Ejemplo n.º 1
0
        /// <summary>
        /// 生成jwtToken
        /// </summary>
        /// <param name="role"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        internal object GenerateJwtToken(string role, AppBlogUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, "Blog"),                    //主题
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //一个唯一标识符
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName.ToString()),
                new Claim(ClaimTypes.Role, role)
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:JWT:JwtKey"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["Authentication:JWT:JwtExpireDays"]));

            var token = new JwtSecurityToken(
                _configuration["Authentication:JWT:JwtIssuer"],
                _configuration["Authentication:JWT:JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        public async Task <IActionResult> LoginAsync([FromForm] LoginModel model)
        {
            List <string> errormessage = new List <string>();

            if (ModelState.IsValid)
            {
                AppBlogUser user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var userroles = await _userManager.GetRolesAsync(user);

                    await _signInManager.SignOutAsync();

                    /*await  _userManager.AddClaimAsync(user, new Claim("sbh", "12345678"));注册的时候添加,可以登陆后附加到cookie中*/
                    //第三个参数,指示在浏览器关闭后登录cookie是否应该保留的标志,true 则按照startup中配置的时间保存,否则就不保存关闭浏览器就失效。
                    var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false);

                    if (result.Succeeded)
                    {
                        _logger.LogLoginInfo("用户登录", nameof(LoginAsync), nameof(AccountController), null, user.UserName, user.Id.ToString());
                        _memoryCache.Set(user.UserName + "_" + user.Id, _user.ClientIP, new DateTimeOffset(DateTime.Now.AddMinutes(60)));//登陆后将客户端连接id存入缓存,缓存时间和cookie 过期时间一致
                        return(new JsonResult(errormessage));
                    }
                    else if (result.IsLockedOut)
                    {
                        ModelState.AddModelError("locked", "被锁定,请联系管理员");
                    }
                    else if (result.IsNotAllowed)
                    {
                        ModelState.AddModelError("notallow", "不被允许访问");
                    }
                    else if (result.RequiresTwoFactor)
                    {
                        ModelState.AddModelError("TwoFactor", "需要双重认证");
                    }
                    else
                    {
                        ModelState.AddModelError("emailorpassworderror", "邮箱或密码错误,请重试!");
                    }
                }
                ModelState.AddModelError("nouser", "用户不存在");
            }

            foreach (var s in ModelState.Values)
            {
                foreach (var p in s.Errors)
                {
                    errormessage.Add(p.ErrorMessage);
                }
            }
            return(new JsonResult(errormessage));
        }
        public async Task <IActionResult> RegisterAsync([FromForm] RegisterModel model)
        {
            List <string> errormessage = new List <string>();

            if (!ModelState.IsValid)
            {
                foreach (var s in ModelState.Values)
                {
                    foreach (var p in s.Errors)
                    {
                        errormessage.Add(p.ErrorMessage);
                    }
                }
                return(new JsonResult(errormessage));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                errormessage.Add("邮箱已被使用");
                return(new JsonResult(errormessage));
            }
            var user2 = await _userManager.FindByNameAsync(model.Name);

            if (user2 != null)
            {
                errormessage.Add("用户名已被使用");
                return(new JsonResult(errormessage));
            }

            var newuser = new AppBlogUser
            {
                UserName   = model.Name,
                Email      = model.Email,
                CreateTime = DateTime.Now
            };
            IdentityResult issuccess = await _userManager.CreateAsync(newuser, model.Password);

            if (issuccess.Succeeded)
            {
                await _signInManager.PasswordSignInAsync(newuser, model.Password, false, false);

                _logger.LogLoginInfo($"{newuser.UserName} 用户注册并登录", nameof(RegisterAsync), nameof(AccountController), null, newuser.UserName, _user.Id.ToString());
                return(new JsonResult(errormessage));
            }
            foreach (var s in issuccess.Errors)
            {
                errormessage.Add(s.Description);
            }
            return(new JsonResult(errormessage));
        }
        public async Task <IActionResult> Login([FromForm] LoginModel model, string returnUrl = null)
        {
            ViewBag.title         = "博客-登录";
            ViewData["ReturnUrl"] = returnUrl;
            ViewBag.container     = "container";//写文章页面和其他页面的样式控制
            if (ModelState.IsValid)
            {
                AppBlogUser user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var userroles = await _userManager.GetRolesAsync(user);

                    await _signInManager.SignOutAsync();

                    /*await  _userManager.AddClaimAsync(user, new Claim("sbh", "12345678"));注册的时候添加,可以登陆后附加到cookie中*/

                    //第三个参数,指示在浏览器关闭后登录cookie是否应该保留的标志,true 则按照startup中配置的时间保存,否则就不保存关闭浏览器就失效。
                    var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false);

                    if (result.Succeeded)
                    {
                        _logger.LogLoginInfo($"{user.UserName} 用户登录", nameof(LoginAsync), nameof(AccountController), null, user.UserName, user.Id.ToString());
                        _memoryCache.Set(user.UserName + "_" + user.Id, _user.ClientIP, new DateTimeOffset(DateTime.Now.AddMinutes(60))); //登陆后将客户端连接id存入缓存,缓存时长和cookie 过期 时间一致
                        return(LocalRedirect(returnUrl));                                                                                 //登录成功
                    }
                    else if (result.IsLockedOut)
                    {
                        ModelState.AddModelError("locked", "被锁定,请联系管理员");
                    }
                    else if (result.IsNotAllowed)
                    {
                        ModelState.AddModelError("notallow", "不被允许访问");
                    }
                    else if (result.RequiresTwoFactor)
                    {
                        ModelState.AddModelError("TwoFactor", "需要双重认证");
                    }
                    else
                    {
                        ModelState.AddModelError("emailorpassworderror", "邮箱或密码错误,请重试!");
                    }
                }
                ModelState.AddModelError("nouser", "用户不存在");
            }
            return(View("Login", model));
        }
Ejemplo n.º 5
0
        public async Task <object> Register([FromBody] RegisterModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                var usernew = new AppBlogUser
                {
                    UserName = model.Email,
                    Email    = model.Email
                };
                var result = await _userManager.CreateAsync(usernew, model.Password);

                if (result.Succeeded)
                {
                    // var role = _userManager.AddToRoleAsync(usernew,"");//注册完成后赋予初始角色
                    await _signInManager.SignInAsync(user, false);

                    return(_JwtHelper.GenerateJwtToken(model.Email, user));
                }
            }
            throw new ApplicationException("UNKNOWN_ERROR");
        }
        public async Task <IActionResult> Register([FromForm] RegisterModel model, string returnUrl = "/")
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    ModelState.AddModelError("EmailExist", "邮箱已被使用");
                    return(View(model));
                }
                var user2 = await _userManager.FindByNameAsync(model.Name);

                if (user2 != null)
                {
                    ModelState.AddModelError("NameExist", "用户名已被使用");
                    return(View(model));
                }
                var newuser = new AppBlogUser
                {
                    UserName   = model.Name,
                    Email      = model.Email,
                    CreateTime = DateTime.Now
                };
                IdentityResult issuccess = await _userManager.CreateAsync(newuser, model.Password);

                if (issuccess.Succeeded)
                {
                    await _signInManager.PasswordSignInAsync(newuser, model.Password, false, false);

                    _logger.LogLoginInfo($"{newuser.UserName} 用户注册并登录", nameof(RegisterAsync), nameof(AccountController), null, newuser.UserName, _user.Id.ToString());
                    return(RedirectToLocal(returnUrl));
                }
            }

            return(View(model));
        }