示例#1
0
    public void JwtSecurityFailureTest()
    {
        string token = new JwtTokenBuilder()
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .AddClaim(new Claim("Email", "*****@*****.**"))
                       .SetPrincipleSignature(_jwtPrincipleSignature)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        IPrincipalSignature principle = _vaultPrincipleSignature.WithIssuer("bad issuer");

        Action act = () => new JwtTokenParserBuilder()
                     .SetPrincipleSignature(principle)
                     .Build()
                     .Parse(token);

        // Failure
        act.Should().Throw <SecurityTokenUnableToValidateException>();

        JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                       .SetPrincipleSignature(_jwtPrincipleSignature)
                                       .Build()
                                       .Parse(token);

        tokenDetails.Should().NotBeNull();
        tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(_jwtVaultTest.LocalCertificateKey.Thumbprint);
    }
示例#2
0
        public IActionResult Create([FromBody] LoginInputModel inputModel)
        {
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = _signInManager.PasswordSignInAsync(inputModel.Username, inputModel.Password, true, lockoutOnFailure: false).Result;
                if (!result.Succeeded)
                {
                    return(Unauthorized());
                }

                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                            .AddSubject("james bond")
                            .AddIssuer("Fiver.Security.Bearer")
                            .AddAudience("Fiver.Security.Bearer")
                            .AddClaim("MembershipId", "111")
                            .AddExpiry(1)
                            .Build();

                //return Ok(token);
                return(Ok(token.Value));
            }

            return(NotFound());
        }
示例#3
0
        public IActionResult Login([FromBody] LoginViewModel inputModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Hibás felhasználónév vagy jelszó!"));
            }

            var currentUser = _userService.getUserByName(inputModel.UserName);

            if (currentUser == null)
            {
                return(NotFound("Nincs ilyen felhasználó regisztrálva!"));
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("Security key required for ShelterApp"))
                        .AddSubject(currentUser.Username)
                        .AddIssuer("ShelterServer")
                        .AddAudience("ShelterApp")
                        .AddClaim("MembershipId", currentUser.Id.ToString())
                        .AddExpiry(300)
                        .Build();

            var responseObject = new LoginResponseModel
            {
                User  = currentUser,
                Token = token.Value
            };

            return(Ok(responseObject));
        }
示例#4
0
    public void GivenIdentity_WhenSigned_ShouldFailWithOtherIdentity()
    {
        var documentId  = new DocumentId("test/unit-tests-identity/identity1");
        var documentId2 = new DocumentId("test/unit-tests-identity/identity2");

        string kid     = Guid.NewGuid().ToString();
        string subject = "*****@*****.**";
        string digest  = Guid.NewGuid().ToString();

        RSAParameters rsaParameter  = Create(documentId);
        RSAParameters rsaParameter2 = Create(documentId2);

        IPrincipalSignature principle  = new PrincipalSignature(kid, "test.com", "spin.com", subject, rsaParameter);
        IPrincipalSignature principle2 = new PrincipalSignature(kid, "test.com", "spin.com", subject, rsaParameter2);

        string token = new JwtTokenBuilder()
                       .SetDigest(digest)
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .SetPrincipleSignature(principle)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        Action test = () => new JwtTokenParserBuilder()
                      .SetPrincipleSignature(principle2)
                      .Build()
                      .Parse(token);

        test.Should().Throw <SecurityTokenSignatureKeyNotFoundException>();
    }
示例#5
0
        public void JwtSecurityTokenBuilderTest()
        {
            const string userId    = "*****@*****.**";
            const string emailText = "Email";
            const string emailId   = "*****@*****.**";

            string token = new JwtTokenBuilder()
                           .SetAudience(new Uri("http://localhost/audience").ToString())
                           .SetIssuer(new Uri("http://localhost/Issuer").ToString())
                           .SetExpires(DateTime.Now.AddDays(10))
                           .SetIssuedAt(DateTime.Now)
                           .SetClaim(new Claim(emailText, emailId))
                           .AddSubject(userId)
                           .SetCertificate(_jwtVaultTest.GetCertificate(_workContext))
                           .Build();

            token.Should().NotBeNullOrEmpty();

            JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                           .AddCertificate(_jwtVaultTest.GetCertificate(_workContext))
                                           .Build()
                                           .Parse(_workContext, token);

            tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(_jwtVaultTest.LocalCertificateKey.Thumbprint);
            tokenDetails.JwtSecurityToken.Subject.Should().Be(userId);
            tokenDetails.JwtSecurityToken.Claims.Any(x => x.Type == emailText && x.Value == emailId).Should().BeTrue();
        }
示例#6
0
        public IActionResult Login([FromBody] LoginModel2 loginModel)
        {
            if (string.IsNullOrEmpty(loginModel.email) || string.IsNullOrEmpty(loginModel.password))
            {
                return(Unauthorized());
            }

            var account = _context.Account.FirstOrDefault(a => a.EMail == loginModel.email);

            if (account == null || account == default(Account))
            {
                return(Unauthorized());
            }
            else
            {
                string preHashText = loginModel.password.Trim() + account.Salt;
                string hashString  = COCOPASS.Helper.NetCoreHelper.Encrypt.ToHMACSHA256HashString(preHashText);
                if (!hashString.Equals(account.Password))
                {
                    return(Unauthorized());
                }
            }

            var token = new JwtTokenBuilder()
                        .AddSubject("ZeYu")
                        .AddSecurityKey(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthenticationToken:SigningKey"])))
                        .AddIssuer(Configuration["AuthenticationToken:Issuer"])
                        .AddAudience(Configuration["AuthenticationToken:Audience"])
                        .AddClaim("MembershipId", account.ID)
                        .AddExpiry(2)
                        .Build();


            return(Ok(token));
        }
示例#7
0
        public async Task <string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
        {
            var claims = new[]
            {
                //new Claim(JwtRegisteredClaimNames.UniqueName, userName),
                //new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                //new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
            };

            //var _claims = new Dictionary<string, string>();
            //_claims.Add(identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role).Type, identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role).Value);
            //_claims.Add(identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id).Type, identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id).Value);

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create())
                        .AddSubject("RCM-API")
                        .AddIssuer(_jwtOptions.Issuer)
                        .AddAudience(_jwtOptions.Audience)
                        .AddClaim(JwtRegisteredClaimNames.UniqueName, userName)
                        .AddClaims(claims)
                        //.AddClaims(_claims)
                        .AddExpiry(100)
                        .Build();

            return(token.Value);
        }
示例#8
0
        public IActionResult Create([FromBody] UserViewModel user)
        {
            var model = _userRepository.GetByEmail(user.Email);

            if (model == null)
            {
                return(Unauthorized());
            }

            var password = new PasswordHasher(_params.Salt).EncryptPassword(user.Password);

            if (model.PasswordHash != password)
            {
                return(Unauthorized());
            }

            JwtTokenBuilder builder = new JwtTokenBuilder()
                                      .AddSecurityKey(JwtToken.GetSecret(_params.Key))
                                      .AddSubject(_params.Subject)
                                      .AddIssuer(_params.Issuer)
                                      .AddAudience(_params.Audience)
                                      .AddClaim(ClaimTypes.Sid, model.Id.ToString())
                                      .AddExpiry(_params.ExpirationTime);

            if (model.IsAdmin)
            {
                builder.AddClaim(_params.AdminClaimName, model.Id.ToString());
            }

            return(Ok(builder.Build().Value));
        }
        public async Task <IActionResult> Login([FromBody] Models.Parameters.LoginModel inputModel)
        {
            var user = UserManager.Users.FirstOrDefault(u => u.UserName == inputModel.Username);

            if (user == null)
            {
                return(Unauthorized());
            }

            var isAuthenticated = await UserManager.CheckPasswordAsync(user, inputModel.Password);

            if (!isAuthenticated)
            {
                return(Unauthorized());
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject("james bond")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();

            if (isAuthenticated)
            {
                var result = await UserManager.SetAuthenticationTokenAsync(user, "Default", "Token", token.Value);
            }

            // return Ok(token);
            return(Ok(token.Value));
        }
        public IHttpActionResult CreateNewToken(AppUser userDetails)
        {
            //Consider right now that authentication is successful.
            JwtTokenBuilder      tokenBuilder = new JwtTokenBuilder();
            SymmetricSecurityKey key          = JwtSecurityKey.Create("abcdefghijklmnopqrstuvwxyz");

            tokenBuilder.AddExpiry(60);
            tokenBuilder.AddSubject("FullStackApp");
            tokenBuilder.AddIssuer("Veracity");
            tokenBuilder.AddAudience("FullStackAppUsers");
            tokenBuilder.AddClaim("userName", userDetails.UserName);
            tokenBuilder.AddClaim("password", userDetails.Password);
            tokenBuilder.AddSecurityKey(key);

            using (workUnit)
            {
                var existingUser = workUnit.Users.
                                   Find(u => u.UserName == userDetails.UserName &&
                                        u.Password == userDetails.Password).FirstOrDefault();
                if (existingUser == null)
                {
                    workUnit.Users.Add(userDetails);
                    workUnit.Complete();
                }
            }
            JwtToken newToken = tokenBuilder.Build();

            return(Ok(newToken.Value));
        }
 public IActionResult Create([FromBody] LoginModel inputModel)
 {
     if (!string.IsNullOrEmpty(inputModel.Username) &&
         !string.IsNullOrEmpty(inputModel.Password))
     {
         var user = this.userRepo.GetByEmailOrNumber(inputModel.Username);
         if (user != null)
         {
             if (user.Password == inputModel.Password)
             {
                 var token = new JwtTokenBuilder()
                             .AddSecurityKey(JwtSecurityKey.Create(user.ID.ToString()))
                             .AddSubject(user.Email)
                             .AddIssuer("Security.Bearer")
                             .AddAudience("Security.Bearer")
                             .AddClaim("IsAdmin", user.IsAdmin)
                             .AddExpiry(5)
                             .Build();
                 return(Ok(token));
             }
             else
             {
                 return(Ok("Wrong Password"));
             }
         }
         else
         {
             return(Ok("Not registered"));
         }
     }
     else
     {
         return(Ok("Email and password blank"));
     }
 }
        public object Login([FromServices] JwtConfiguration tokenConfigurations, [FromBody] LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(GetErros());
            }

            string token = string.Empty;

            var user = UserRepositoryMock.GetUser(model.Username, model.Password);

            if (user != null)
            {
                token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(tokenConfigurations.JwtKey))
                        .AddSubject(user.Name)
                        .AddIssuer(tokenConfigurations.Issuer)
                        .AddAudience(tokenConfigurations.Audience)
                        .AddNameId(user.Username)
                        .AddExpiryDays(tokenConfigurations.Days)
                        //Adicionado um claim com os perfis de uso.
                        .AddClaimsPermission(user.Permissions)
                        .Build();

                return(new { token });
            }
            else
            {
                return(BadRequest(
                           new { message = "Usuário ou senha inválidos!" }
                           ));
            }
        }
示例#13
0
        public async Task <IActionResult> Create([FromBody] LoginRequest inputModel)
        {
            if (!(inputModel.Username == "test" && inputModel.Password == "1234"))
            {
                return(Unauthorized());
            }

            var result = new LoginResponse()
            {
                Id       = Guid.NewGuid().ToString(),
                Name     = "test",
                Surname  = "test",
                UserName = "******"
            };
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject($"{result.Name} {result.Surname}")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("UserName", result.UserName)
                        .AddClaim("MembershipId", result.Id)
                        //.AddClaim("roles", string.Join(",", result.Roles))
                        .AddExpiry(60)
                        .Build();

            return(Ok(token));
        }
示例#14
0
    public void JwtSecurityTokenBuilderTest()
    {
        const string userId    = "*****@*****.**";
        const string emailText = "Email";
        const string emailId   = "*****@*****.**";

        IPrincipalSignature principle = _jwtPrincipleSignature.WithSubject(userId);

        string token = new JwtTokenBuilder()
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .AddClaim(new Claim(emailText, emailId))
                       .SetPrincipleSignature(principle)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                       .SetPrincipleSignature(_jwtPrincipleSignature)
                                       .Build()
                                       .Parse(token);

        tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(jwtKeyId);
        tokenDetails.JwtSecurityToken.Subject.Should().Be(userId);
        tokenDetails.JwtSecurityToken.Claims.Any(x => x.Type == emailText && x.Value == emailId).Should().BeTrue();
    }
示例#15
0
        public TokensData UpdateAccessToken(Tokens tokens, int id, out dynamic key)
        {
            var user = userService.GetUserByName(tokens);

            key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"]));
            //var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            Console.WriteLine(key);
            var expiry = DateTime.Now.AddMinutes(5);

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration["SecurityKey"]))
                        .AddSubject("test123 test123")
                        .AddIssuer("SalesMarket.Security.Bearer")
                        .AddAudience("SalesMarket.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();
            TokensData tokensData = new TokensData
            {
                Token       = token.Value,
                ExpiryToken = expiry,
                AddedDate   = DateTime.Now,
                LastUpdate  = DateTime.Now,
                UsersId     = id
            };

            return(tokensData);
        }
示例#16
0
        private object GenerateToken(IList <string> roles, User user, int role, string currHostUrl)
        {
            var tokenBuilder = new JwtTokenBuilder()
                               .AddSecurityKey(JwtSecurityKey.Create())
                               .AddSubject("token authentication")
                               .AddIssuer("Fiver.Security.Bearer")
                               .AddAudience("Fiver.Security.Bearer")
                               .AddClaim("MembershipId", "111", roles)
                               .AddExpiry(360000)
                               .Build();
            var data = new
            {
                user.Id,
                Username = user.UserName,
                user.Email,
                Token    = tokenBuilder.Value,
                FullName = user.FirstName + " " + user.LastName,
                user.FirstName,
                user.LastName,
                user.PhoneNumber,
                //Birthdate = user.Birthdate != null ? user.Birthdate.Value.ToShortDateString() : null,
                //user.Address,
                RoleId = role,
                //ProfilePic = user.ProfilePic == null ? null : currHostUrl + user.ProfilePic,
                //CoverPic = user.CoverPic == null ? null : currHostUrl + user.CoverPic,
                Validity = tokenBuilder.ValidTo
            };

            return(data);
        }
示例#17
0
        public IActionResult RefreshToken([FromBody] UserLogin data)
        {
            var _refreshToken = db.RefreshTokens.SingleOrDefault(m => m.Refreshtoken == data.refreshToken);
            var role          = db.Roles.Where(x => x.Id == data.RoleId).FirstOrDefault().Name;

            if (_refreshToken == null)
            {
                return(Ok(null));
            }
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration.GetValue <string>("JwtSecretKey")))
                        .AddIssuer(_configuration.GetValue <string>("JwtIssuer"))
                        .AddAudience(_configuration.GetValue <string>("JwtAudience"))
                        .AddExpiry(60)
                        .AddClaim("Email", data.username)
                        .AddRole(role)
                        .Build();

            _refreshToken.Refreshtoken = Guid.NewGuid().ToString();
            db.RefreshTokens.Update(_refreshToken);
            db.SaveChanges();
            data.Token        = token.Value;
            data.refreshToken = _refreshToken.Refreshtoken;

            return(Ok(data));
        }
示例#18
0
        public async Task <IActionResult> GetToken([FromBody] LoginRequestModel model)
        {
            //Get user & validate password.
            var user = await _userSecurityMgr.GetUserForLogin(model.Username, model.Password);

            //if that didn't return a user, then either name or password is not valid, so nah.
            if (user == null)
            {
                return(Unauthorized());
            }

            var tokenBuilder = new JwtTokenBuilder()
                               .AddSecurityKey(JwtSecurityKey.Create(_settingsService.JwtSecret))
                               .AddSubject(user.UserName)
                               .AddIssuer(_settingsService.JwtIssuer)
                               .AddAudience(_settingsService.JwtAudience)
                               .AddClaim("MembershipId", user.Id);

            //add all known roles to claim.
            foreach (var role in _userSecurityMgr.GetRolesForUser(user))
            {
                tokenBuilder = tokenBuilder.AddClaim("roles", role);
            }

            tokenBuilder = tokenBuilder
                           .AddExpiry(_settingsService.TokenLifeTimeInMinutes);

            var token = tokenBuilder.Build();

            return(Ok(token.Value));
        }
        //[Route("logOut/{refreshTokenId}")]
        //[HttpGet]
        //public async Task<RepositoryResponse<bool>> Logout(string refreshTokenId)
        //{
        //    var result = await RefreshTokenViewModel.Repository.RemoveListModelAsync(t => t.Id == refreshTokenId);
        //    return result;
        //}

        //[Route("logOutOther/{refreshTokenId}")]
        //[HttpGet]
        //public async Task<RepositoryResponse<bool>> LogoutOther(string refreshTokenId)
        //{
        //    return await RefreshTokenViewModel.LogoutOther(refreshTokenId);
        //}

        /*
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
         * {
         *  // Ensure the user has gone through the username & password screen first
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  var model = new LoginWith2faViewModel { RememberMe = rememberMe };
         *  ViewData["ReturnUrl"] = returnUrl;
         *
         *  return View(model);
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
         *  }
         *
         *  var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
         *
         *  var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
         *
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  else if (result.IsLockedOut)
         *  {
         *      _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
         *      return RedirectToAction(nameof(Login));
         *  }
         *  else
         *  {
         *      _logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
         *      ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
         *      return View();
         *  }
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
         * {
         *  // Ensure the user has gone through the username & password screen first
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  ViewData["ReturnUrl"] = returnUrl;
         *
         *  return View();
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
         *
         *  var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
         *
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  if (result.IsLockedOut)
         *  {
         *      _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
         *      return RedirectToAction(nameof(Login));
         *  }
         *  else
         *  {
         *      _logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id);
         *      ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
         *      return View();
         *  }
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public IActionResult ExternalLogin(string provider, string returnUrl = null)
         * {
         *  // Request a redirect to the external login provider.
         *  var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
         *  var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
         *  return Challenge(properties, provider);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
         * {
         *  if (remoteError != null)
         *  {
         *      ErrorMessage = $"Error from external provider: {remoteError}";
         *      return RedirectToAction(nameof(Login));
         *  }
         *  var info = await _signInManager.GetExternalLoginInfoAsync();
         *  if (info == null)
         *  {
         *      return RedirectToAction(nameof(Login));
         *  }
         *
         *  // Sign in the user with this external login provider if the user already has a login.
         *  var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  if (result.IsLockedOut)
         *  {
         *      return RedirectToAction(nameof(Login)); // LogOut
         *  }
         *  else
         *  {
         *      // If the user does not have an account, then ask the user to create an account.
         *      ViewData["ReturnUrl"] = returnUrl;
         *      ViewData["LoginProvider"] = info.LoginProvider;
         *      var email = info.Principal.FindFirstValue(ClaimTypes.Email);
         *      return View("ExternalLogin", new ExternalLoginViewModel { Email = email });
         *  }
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      // Get the information about the user from the external login provider
         *      var info = await _signInManager.GetExternalLoginInfoAsync();
         *      if (info == null)
         *      {
         *          throw new ApplicationException("Error loading external login information during confirmation.");
         *      }
         *      var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
         *      var result = await _userManager.CreateAsync(user);
         *      if (result.Succeeded)
         *      {
         *          result = await _userManager.AddLoginAsync(user, info);
         *          if (result.Succeeded)
         *          {
         *              await _signInManager.SignInAsync(user, isPersistent: false);
         *              _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
         *              return RedirectToLocal(returnUrl);
         *          }
         *      }
         *      AddErrors(result);
         *  }
         *
         *  ViewData["ReturnUrl"] = returnUrl;
         *  return View(nameof(ExternalLogin), model);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> ConfirmEmail(string userId, string code)
         * {
         *  if (userId == null || code == null)
         *  {
         *      return RedirectToAction("Index", "Home");
         *  }
         *  var user = await _userManager.FindByIdAsync(userId);
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load user with ID '{userId}'.");
         *  }
         *  var result = await _userManager.ConfirmEmailAsync(user, code);
         *  return View(result.Succeeded ? "ConfirmEmail" : "Error");
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ForgotPassword()
         * {
         *  return View();
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      var user = await _userManager.FindByEmailAsync(model.Email);
         *      if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
         *      {
         *          // Don't reveal that the user does not exist or is not confirmed
         *          return RedirectToAction(nameof(ForgotPasswordConfirmation));
         *      }
         *
         *      // For more information on how to enable account confirmation and password reset please
         *      // visit https://go.microsoft.com/fwlink/?LinkID=532713
         *      var code = await _userManager.GeneratePasswordResetTokenAsync(user);
         *      var callbackUrl = "";
         *      await _emailSender.SendEmailAsync(model.Email, "Reset Password",
         *         $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
         *      return RedirectToAction(nameof(ForgotPasswordConfirmation));
         *  }
         *
         *  // If we got this far, something failed, redisplay form
         *  return View(model);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ForgotPasswordConfirmation()
         * {
         *  return View();
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ResetPassword(string code = null)
         * {
         *  if (code == null)
         *  {
         *      throw new ApplicationException("A code must be supplied for password reset.");
         *  }
         *  var model = new ResetPasswordViewModel { Code = code };
         *  return View(model);
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *  var user = await _userManager.FindByEmailAsync(model.Email);
         *  if (user == null)
         *  {
         *      // Don't reveal that the user does not exist
         *      return RedirectToAction(nameof(ResetPasswordConfirmation));
         *  }
         *  var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
         *  if (result.Succeeded)
         *  {
         *      return RedirectToAction(nameof(ResetPasswordConfirmation));
         *  }
         *  AddErrors(result);
         *  return View();
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ResetPasswordConfirmation()
         * {
         *  return View();
         * }
         *
         * [HttpGet]
         * public IActionResult AccessDenied()
         * {
         *  return View();
         * }
         *
         #region Helpers
         *
         * private void AddErrors(IdentityResult result)
         * {
         *  foreach (var error in result.Errors)
         *  {
         *      ModelState.AddModelError(string.Empty, error.Description);
         *  }
         * }
         *
         * private IActionResult RedirectToLocal(string returnUrl)
         * {
         *  if (Url.IsLocalUrl(returnUrl))
         *  {
         *      return Redirect(returnUrl);
         *  }
         *  else
         *  {
         *      return RedirectToAction("Index", "Home");
         *  }
         * }
         *
         #endregion Helpers
         *
         * //[AllowAnonymous]
         * [HttpPost]
         * public async Task<JsonResult> GenerateToken([FromBody] LoginViewModel model)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      var user = await _userManager.FindByEmailAsync(model.Email);
         *
         *      if (user != null)
         *      {
         *          var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
         *          if (result.Succeeded)
         *          {
         *              var claims = new[]
         *              {
         * new Claim(JwtRegisteredClaimNames.Sub, user.Email),
         * new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
         * };
         *
         *              var creds = SWCmsConstants.AuthConfiguration.SigningCredentials;
         *
         *              var token = new JwtSecurityToken(SWCmsConstants.AuthConfiguration.AuthTokenIssuer,
         *                SWCmsConstants.AuthConfiguration.AuthTokenIssuer,
         *                claims,
         *                expires: DateTime.Now.AddMinutes(30),
         *                signingCredentials: creds);
         *
         *              return new JsonResult(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
         *          }
         *      }
         *  }
         *  return new JsonResult("Could not create token");
         * }
         *
         */

        private AccessTokenViewModel GenerateAccessToken(ApplicationUser user)
        {
            //string refreshToken = Guid.NewGuid().ToString();
            //var dtIssued = DateTime.UtcNow;
            //var dtExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration);
            //var dtRefreshTokenExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration);

            //RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel(
            //            new RefreshToken()
            //            {
            //                Id = refreshToken,
            //                Email = user.Email,
            //                IssuedUtc = dtIssued,
            //                ClientId = SWCmsConstants.AuthConfiguration.Audience,
            //                //Subject = SWCmsConstants.AuthConfiguration.Audience,
            //                ExpiresUtc = dtRefreshTokenExpired
            //            });

            //var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync();

            //if (saveRefreshTokenResult.IsSucceed)
            //{
            //    AccessTokenViewModel token = new AccessTokenViewModel()
            //    {
            //        Access_token = GenerateToken(user, dtExpired, refreshToken),
            //        //Refresh_token = vmRefreshToken.Id,
            //        Token_type = SWCmsConstants.AuthConfiguration.TokenType,
            //        Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration,
            //        //UserData = user,
            //        Issued = dtIssued,
            //        Expires = dtExpired,
            //    };
            //    return token;
            //}
            //else
            //{
            //    return null;
            //}

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(SWCmsConstants.JWTSettings.SECRET_KEY))
                        .AddSubject(user.UserName)
                        .AddIssuer(SWCmsConstants.JWTSettings.ISSUER)
                        .AddAudience(SWCmsConstants.JWTSettings.AUDIENCE)
                        //.AddClaim("MembershipId", "111")
                        .AddExpiry(SWCmsConstants.JWTSettings.EXPIRED_IN)
                        .Build();
            AccessTokenViewModel access_token = new AccessTokenViewModel()
            {
                Access_token = token.Value, //GenerateToken(user, dtExpired, refreshToken),
                //Refresh_token = vmRefreshToken.Id,
                Token_type = SWCmsConstants.AuthConfiguration.TokenType,
                Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration,
                //UserData = user,
                Issued  = DateTime.UtcNow,
                Expires = token.ValidTo
            };

            return(access_token);
        }
示例#20
0
    public void GivenJwtSigned_ShouldValidate()
    {
        string kid     = Guid.NewGuid().ToString();
        string subject = "*****@*****.**";
        string digest  = Guid.NewGuid().ToString();

        IPrincipalSignature principle = new PrincipalSignature(kid, "test.com", "spin.com", subject);

        string token = new JwtTokenBuilder()
                       .SetDigest(digest)
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .SetPrincipleSignature(principle)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                       .SetPrincipleSignature(principle)
                                       .Build()
                                       .Parse(token);

        tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(kid);
        tokenDetails.JwtSecurityToken.Subject.Should().Be(subject);
    }
示例#21
0
    public void GivenIdentity_WhenSigned_ShouldValidate()
    {
        var documentId = new DocumentId("test/unit-tests-identity/identity1");

        string kid     = Guid.NewGuid().ToString();
        string subject = "*****@*****.**";
        string digest  = Guid.NewGuid().ToString();

        RSAParameters rsaParameter = Create(documentId);

        IPrincipalSignature principle = new PrincipalSignature(kid, "test.com", "spin.com", subject, rsaParameter);

        string token = new JwtTokenBuilder()
                       .SetDigest(digest)
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .SetPrincipleSignature(principle)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                       .SetPrincipleSignature(principle)
                                       .Build()
                                       .Parse(token);

        tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(kid);
        tokenDetails.JwtSecurityToken.Subject.Should().Be(subject);
    }
示例#22
0
    public void GivenJwtSigned_WhenAnotherPrincipleIsUsed_ShouldFailValidate()
    {
        string kid     = Guid.NewGuid().ToString();
        string kid2    = Guid.NewGuid().ToString();
        string subject = "*****@*****.**";
        string digest  = Guid.NewGuid().ToString();

        IPrincipalSignature principle  = new PrincipalSignature(kid, "test.com", "spin.com", subject);
        IPrincipalSignature principle2 = new PrincipalSignature(kid2, "test2.com", "spin2.com", subject);

        string token = new JwtTokenBuilder()
                       .SetDigest(digest)
                       .SetExpires(DateTime.Now.AddDays(10))
                       .SetIssuedAt(DateTime.Now)
                       .SetPrincipleSignature(principle)
                       .Build();

        token.Should().NotBeNullOrEmpty();

        Action test = () => new JwtTokenParserBuilder()
                      .SetPrincipleSignature(principle2)
                      .Build()
                      .Parse(token);

        test.Should().Throw <SecurityTokenUnableToValidateException>();
    }
示例#23
0
        public async Task <IActionResult> Create([FromBody] RegistrationLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Unauthorized());
            }

            var userVerified = await _acctSvc.VerifyUserAsync(model);

            if (userVerified != null)
            {
                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(_config.GetSection("JwtSettings:SecurityKey").Value))
                            .AddSubject(model.Email)
                            .AddIssuer(_config.GetSection("AppConfiguration:Issuer").Value)
                            .AddAudience(_config.GetSection("AppConfiguration:Issuer").Value)
                            //.AddClaim("SellerId", userVerified.Id.ToString())
                            .AddExpiry(10)
                            .Build();

                TokenModel tokenModel = new TokenModel
                {
                    AccessToken = token.Value,
                    SellerId    = userVerified.Id,
                    Email       = model.Email
                };

                return(Ok(tokenModel));
            }

            return(BadRequest());
        }
示例#24
0
        public async Task <IActionResult> Create([FromBody] JwtLoginInputModel inputModel)
        {
            var user = await _userManager.FindByNameAsync(inputModel.Username);

            if (user == null)
            {
                return(Unauthorized());
            }

            // Validate the username/password parameters and ensure the account is not locked out.
            var result = await _signInManager.CheckPasswordSignInAsync(user, inputModel.Password, lockoutOnFailure : true);

            if (!result.Succeeded)
            {
                return(Unauthorized());
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject("james bond")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();

            //return Ok(token);
            return(Ok(token.Value));
        }
示例#25
0
        public void JwtSecurityFailureTest()
        {
            var issuer = new Uri("http://localhost/Issuer");

            string token = new JwtTokenBuilder()
                           .SetIssuer(issuer.ToString())
                           .SetExpires(DateTime.Now.AddDays(10))
                           .SetIssuedAt(DateTime.Now)
                           .SetClaim(new Claim("Email", "*****@*****.**"))
                           .SetCertificate(_jwtVaultTest.GetCertificate(_workContext))
                           .Build();

            token.Should().NotBeNullOrEmpty();

            JwtTokenDetails tokenDetails = new JwtTokenParserBuilder()
                                           .AddCertificate(_vaultData.GetCertificate(_workContext))
                                           .AddValidIssuer(issuer.ToString())
                                           .Build()
                                           .Parse(_workContext, token);

            // Failure
            tokenDetails.Should().BeNull();

            tokenDetails = new JwtTokenParserBuilder()
                           .AddCertificate(_jwtVaultTest.GetCertificate(_workContext))
                           .AddCertificate(_vaultData.GetCertificate(_workContext))
                           .AddValidIssuer(issuer.ToString())
                           .Build()
                           .Parse(_workContext, token);

            tokenDetails.Should().NotBeNull();
            tokenDetails.JwtSecurityToken.Header.Kid.Should().Be(_jwtVaultTest.LocalCertificateKey.Thumbprint);
        }
        public IActionResult Login(LoginView user)
        {
            //if (ModelState.IsValid)
            //{
            //    MembershipContext _userContext = _membershipService.ValidateUser(user.UserName, user.Password);
            //    if (_userContext.User != null)
            //    {
            //        Request.HttpContext.Response.Headers.Add("UserName", _userContext.Principal.Identity.Name);
            //        return new ContentResult { Content = "Successed!", StatusCode = (int)HttpStatusCode.OK, ContentType = "txt/html" };
            //    }
            //    else
            //        return new ContentResult { Content = "Failed", StatusCode = (int)HttpStatusCode.OK, ContentType = "txt/html" };
            //}
            //else
            //    return new ContentResult { StatusCode = (int)HttpStatusCode.BadRequest };


            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject("james bond")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();

            return(new JsonResult(token));
        }
示例#27
0
        public Entity.API.LoginResponse Buscar(string login, string password)
        {
            var usr = _UsuarioRepository.Buscar(login, password);

            if (usr != null && !string.IsNullOrEmpty(usr.Login))
            {
                IConfigurationSection jwtAppSettingOptions = _configuration.GetSection("JwtIssuerOptions");
                var secretKey  = jwtAppSettingOptions["SecretKey"];
                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(signingKey.ToString()))
                            .AddIssuer(jwtAppSettingOptions["Issuer"])
                            .AddAudience(jwtAppSettingOptions["Audience"])
                            .AddExpiry(1)
                            .AddClaim(ClaimTypes.NameIdentifier, usr.Nome)
                            .AddClaim(ClaimTypes.Name, usr.Login)
                            .AddClaim(ClaimTypes.Role, "USUARIO")
                            .Build();

                var resultMapped = _mapper.Map <Entity.API.LoginResponse>(usr);
                resultMapped.ChaveJwt = token.Value;

                return(resultMapped);
            }
            else
            {
                return(new Entity.API.LoginResponse());
            }
        }
示例#28
0
        private async Task <LoginResp> Login(string loginName, string password, string authCode, byte clientType, string clientId, bool regist = false)
        {
            var resp = new LoginResp();

            var ip      = Request.GetClientIP();
            var website = Request.GetReferer();

            var result = await _userService.Login(loginName, password, ip, website, clientType, clientId);

            if (result.NonzeroCode)
            {
                return(resp.Fail(result.Msg));
            }

            // 生成本次登录的标识
            string loginId = $"__{ip}_{DateTime.Now.ToString("yyMMddHHmmssfffffff")}";

            // 生成 Token
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_jwtOptions.Secret))
                        .AddIssuer(_jwtOptions.Issuer)
                        .AddAudience(_jwtOptions.Audience)
                        .AddClaim(Constants.LOGINNAME, loginName)
                        .AddClaim(Constants.LOGINID, loginId)
                        .AddExpiry(_jwtOptions.Expiry)
                        .Build();

            // 写入缓存,以便 TokenSessionFilter使用
            await _redisClient.GetDatabase().StringSetAsync(loginName, loginId, TimeSpan.FromMinutes(_jwtOptions.Expiry));

            resp.AccessToken = token.Value;
            resp.TokenType   = "Bearer";
            return(resp);
        }
示例#29
0
        public JsonResult Create([FromBody] LoginInputModel inputModel)
        {
            var audienceConfig       = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var expiresTime          = ConvertHelper.ConvertToInt(audienceConfig["ExpiresTime"]);
            var iss = audienceConfig["Iss"];
            var aud = audienceConfig["Aud"];

            if (inputModel.username == "admin" && inputModel.password == "12" && inputModel.client_secret == symmetricKeyAsBase64)
            {
                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(inputModel.client_secret))
                            .AddSubject(inputModel.username)
                            .AddIssuer(iss)
                            .AddAudience(aud)
                            .AddClaim("scope", "openid pv btv tk bbt")
                            .AddClaim("NameSpace", inputModel.name_space)
                            .AddExpiry(expiresTime)
                            .Build();

                return(this.ToJson(token));
            }
            else
            {
                return(this.ToJson(Unauthorized()));
            }
        }
        public IActionResult Create([FromBody] LoginInputModel inputModel)
        {
            if (!checkPassword(inputModel.Password))
            {
                return(Unauthorized());
            }
            string ip = HttpContext.Connection.RemoteIpAddress.ToString();

            if (_ipService.Ips.ContainsKey(ip))
            {
                _ipService.Ips[ip] = DateTime.Now;
            }
            else
            {
                _ipService.Ips.Add(ip, DateTime.Now);
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration["jwtsecret"]))
                        .AddSubject("admin")
                        .AddIssuer("nearlyeveryone")
                        .AddAudience("nearlyeveryone")
                        .AddClaim("admin", "admin")
                        .AddExpiry(600)
                        .Build();

            return(Json(token));
        }