示例#1
0
        public async Task <IActionResult> Authorize([FromBody] AuthenticationDto model)
        {
            var found = await _administrationManager.Get(model.UserName);

            if (found != null && found.DeactivatedDate == null &&
                _passwordStorage.VerifyHashedPassword(new User(), found.PasswordHash, model.Password) ==
                PasswordVerificationResult.Success)
            {
                var now = DateTime.UtcNow;

                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, found.UserName),                                                                         // The subject of the token.
                    new Claim(JwtRegisteredClaimNames.Email, found.Email),                                                                          // The email.
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),                                                              // Unique identifier for the JWT. Can be used to prevent the JWT from being replayed.This is helpful for a one time use token.
                    new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64) // The time the JWT was issued. Can be used to determine the age of the JWT.
                };
                // Include user claims
                claims.AddRange(found.Claims.Select(foundClaim => new Claim(foundClaim.ClaimType, foundClaim.ClaimValue)));
                // Include user Id
                claims.Add(new Claim(ClaimTypes.PrimarySid, found.Id.ToString()));
                // Include email
                claims.Add(new Claim(ClaimTypes.Email, found.Email));
                // Include the name in the claims
                claims.Add(found.Profile != null
                    ? new Claim(ClaimTypes.Name, $"{found.Profile.FirstName} {found.Profile.LastName}")
                    : new Claim(ClaimTypes.Name, $"{found.UserName}"));

                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.Secret));

                var jwt = new JwtSecurityToken(
                    issuer: _settings.Value.Issuer,
                    audience: _settings.Value.Audience,
                    claims: claims,
                    notBefore: now,
                    // Token will live 48 hours
                    expires: now.Add(TimeSpan.FromHours(48)),
                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                    );
                var encodedJwt   = new JwtSecurityTokenHandler().WriteToken(jwt);
                var responseJson = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)TimeSpan.FromHours(48).TotalSeconds
                };
                return(new JsonResult(responseJson));
            }
            return(new JsonResult(string.Empty));
        }
示例#2
0
        public async void CanUpdateUser()
        {
            var random = DateTime.Now.ToString("MMddyyhhmmssfff");
            // Create
            var user = new User(Guid.Empty
                                , $"{DataGenerator.GenerateRandomName(1).FirstOrDefault()?.Item1}-{random}"
                                , $"{DataGenerator.GenerateRandomName(1).FirstOrDefault().Item1}-{random}@testing.com"
                                , true
                                , _passwordStorage.HashPassword(new User(), "testdb99!!")
                                , Guid.NewGuid().ToString()
                                , true
                                , true
                                , false
                                , false
                                , 0
                                , DateTime.UtcNow
                                , DateTime.UtcNow);

            user.Profile = new UserProfile(user.Id
                                           , DataGenerator.GenerateRandomName(1).FirstOrDefault().Item1
                                           , DataGenerator.GenerateRandomName(1).FirstOrDefault().Item2
                                           , Guid.Parse("5ebf5cca-df92-49c6-ae5f-f3c9670bf9d3")
                                           , Guid.Parse("2af6ff6c-8bb8-46f0-b27e-81def1b76b64")
                                           , Guid.Parse("8a29a4ab-62a7-4a06-b2fa-46a40f449a84"));
            user.PhoneNumber = "123-456-7890";
            var id = await _administrationManager.Create(user);

            Assert.True(id != Guid.Empty, "Failed to create user");
            // Find
            var found = await _administrationManager.Get(id);

            Assert.True(found != null, "Failed to find user");
            // Update
            found.PhoneNumber = "999-999-9999";
            var update = await _administrationManager.Update(found);

            Assert.True(update, "Failed to update user");
        }
 public async Task <User> User(Guid id)
 {
     return(await _administrationManager.Get(id));
 }