Пример #1
0
        private async Task <IActionResult> CreateToken(bool rememberMe, OmbiUser user)
        {
            var roles = await _userManager.GetRolesAsync(user);

            if (roles.Contains(OmbiRoles.Disabled))
            {
                return(new UnauthorizedResult());
            }

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("Id", user.Id)
            };

            claims.AddRange(roles.Select(role => new Claim("role", role)));
            if (user.Email.HasValue())
            {
                claims.Add(new Claim("Email", user.Email));
            }

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(StartupSingleton.Instance.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


            var token = new JwtSecurityToken(
                claims: claims,
                expires: rememberMe ? DateTime.Now.AddYears(1) : DateTime.Now.AddDays(7),
                signingCredentials: creds,
                audience: "Ombi", issuer: "Ombi"
                );
            var accessToken = new JwtSecurityTokenHandler().WriteToken(token);

            if (rememberMe)
            {
                // Save the token so we can refresh it later
                //await _token.CreateToken(new Tokens() {Token = accessToken, User = user});
            }

            user.LastLoggedIn = DateTime.UtcNow;

            await _userManager.UpdateAsync(user);

            return(new JsonResult(new
            {
                access_token = accessToken,
                expiration = token.ValidTo
            }));
        }
Пример #2
0
        public override async Task OnConnectedAsync()
        {
            var identity    = (ClaimsIdentity)Context.User.Identity;
            var userIdClaim = identity.Claims.FirstOrDefault(x => x.Type.Equals("Id", StringComparison.InvariantCultureIgnoreCase));

            if (userIdClaim == null)
            {
                await base.OnConnectedAsync();

                return;
            }

            var user = await _userManager.Users.
                       FirstOrDefaultAsync(x => x.Id == userIdClaim.Value);

            var claims = await _userManager.GetRolesAsync(user);

            UsersOnline.TryAdd(Context.ConnectionId, new HubUsers
            {
                UserId = userIdClaim.Value,
                Roles  = claims
            });
            await base.OnConnectedAsync();
        }