コード例 #1
0
        public async Task <AuthenticationResultModel> GenerateJwtByUserPass(AuthenticationRequestModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(AuthenticationResultModel.Failed($"No Accounts Registered with {model.Email}."));
            }

            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var refreshToken = new RefreshToken();
                if (user.RefreshTokens.Any(a => a.IsActive))
                {
                    refreshToken = user.RefreshTokens.FirstOrDefault(a => a.IsActive);
                }
                else
                {
                    refreshToken = RefreshTokenGenerator.CreateRefreshToken();
                    user.RefreshTokens.Add(refreshToken);
                    _context.Update(user);
                    _context.SaveChanges();
                }

                return(await GetAuthenticationResultModel(user, refreshToken));
            }

            return(AuthenticationResultModel.Failed("Incorrect Credentials for user {user.Email}."));
        }
コード例 #2
0
        public async Task <IActionResult> Login([FromBody] AuthenticationRequestModel userForAuthentication)
        {
            var user = await _userManager.FindByNameAsync(userForAuthentication.UserName);

            if (user == null)
            {
                return(StatusCode(401, new AuthenticationResponseModel {
                    ErrorMessage = "No such user"
                }));
            }
            if (!await _userManager.CheckPasswordAsync(user, userForAuthentication.Password))
            {
                return(StatusCode(401, new AuthenticationResponseModel {
                    ErrorMessage = "Wrong password"
                }));
            }
            if (user.IsBanned)
            {
                return(StatusCode(401, new AuthenticationResponseModel {
                    ErrorMessage = "User is banned"
                }));
            }

            var tokens = await _jwtHandler.GenerateTokensForUser(user);

            return(Ok(new AuthenticationResponseModel {
                IsAuthSuccessful = true, Tokens = tokens
            }));
        }
コード例 #3
0
        public async Task <AuthenticationResponseModel> Authenticate(AuthenticationRequestModel model)
        {
            if (model.grant_type == "password")
            {
                if (model.scope == "my cool app")
                {
                    var userEntity = await userStore.FindUserProfile(model.client_id);

                    if (userEntity == null)
                    {
                        return(null);
                    }

                    if (userEntity.Password == model.client_secret)
                    {
                        var token = await jWTFactoryService.CreateToken(userEntity);

                        return(new AuthenticationResponseModel
                        {
                            access_token = token,
                            token_type = "Bearer"
                        });
                    }
                }
            }
            return(null);
        }
コード例 #4
0
        public async Task <IActionResult> AuthenticateByUserPass(AuthenticationRequestModel model)
        {
            var authenticationResult = await _authenticationService.GenerateJwtByUserPass(model);

            Response.SetRefreshToken(authenticationResult.RefreshToken);
            return(Ok(authenticationResult));
        }
コード例 #5
0
        public async Task <AuthenticationResponseModel> GetTokenAsync(AuthenticationRequestModel model)
        {
            var response = new AuthenticationResponseModel();
            var user     = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                response.IsAuthenticated = false;
                response.Message         = $"No Accounts Registered with {model.Email}.";
                return(response);
            }
            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                response.IsAuthenticated = true;
                JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user);

                response.Token    = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                response.Email    = user.Email;
                response.UserName = user.UserName;
                var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

                response.Roles = rolesList.ToList();
                return(response);
            }
            response.IsAuthenticated = false;
            response.Message         = $"Incorrect Credentials for user {user.Email}.";
            return(response);
        }
コード例 #6
0
        public async Task <TokensResponseModel> Loggin(AuthenticationRequestModel authenticationRequestModel, [FromServices] IJwtSigningEncodingKey signingEncodingKey)
        {
            var result = await _userService.Loggin(await _userService.GetIdByEmail(authenticationRequestModel.Email), authenticationRequestModel.Password);

            var id = await _userService.GetIdByEmail(authenticationRequestModel.Email);

            User user = await _userManager.FindByIdAsync(id);

            var roles = await _userManager.GetRolesAsync(user);

            string role = roles.FirstOrDefault();

            if (result.Succeeded)
            {
                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, authenticationRequestModel.Email),
                    new Claim(ClaimTypes.Role, role)
                };

                var refreshClaims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, authenticationRequestModel.Email)
                };

                var token = new JwtSecurityToken(
                    issuer: "Test",
                    audience: "Bookstore",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(10),
                    signingCredentials: new SigningCredentials(signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm)
                    );

                var refreshToken = new JwtSecurityToken(
                    issuer: "Test",
                    audience: "Bookstore",
                    claims: refreshClaims,
                    expires: DateTime.Now.AddDays(60),
                    signingCredentials: new SigningCredentials(signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm)
                    );


                string jwtToken        = new JwtSecurityTokenHandler().WriteToken(token);
                string refreshJwtToken = new JwtSecurityTokenHandler().WriteToken(refreshToken);
                TokensResponseModel tokensResponseModel = new TokensResponseModel();
                tokensResponseModel.AccessToken  = jwtToken;
                tokensResponseModel.RefreshToken = refreshJwtToken;
                tokensResponseModel.Role         = role;
                tokensResponseModel.Id           = user.Id;
                await _userManager.SetAuthenticationTokenAsync(user, String.Empty, "RefreshToken", refreshJwtToken);

                return(tokensResponseModel);
            }

            return(null);
        }
コード例 #7
0
 public async Task <IActionResult> Auth(AuthenticationRequestModel model)
 {
     try
     {
         return(Ok(await authenticationService.Authenticate(model)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
コード例 #8
0
        public IResponse Authentication(AuthenticationRequestModel authentication)
        {
            var auth  = _mapperAdapter.Map <AuthenticationRequestModel, Authentication>(authentication);
            var token = _authService.Authentication(auth);

            if (token == Guid.Empty)
            {
                return(new AuthenticationOkResponseModel("Email/Cpf or Senha invalid."));
            }

            return(_mapperAdapter.Map <Guid, AuthenticationOkResponseModel>(token));
        }
コード例 #9
0
        public static void Test_Can_JSON_Serialize_To_NonNull_Non_Whitespace(string username, string password)
        {
            //arrange
            AuthenticationRequestModel authModel = new AuthenticationRequestModel(username, password);

            //act
            string serializedModel = JsonConvert.SerializeObject(authModel);

            //assert
            Assert.NotNull(serializedModel);
            Assert.IsNotEmpty(serializedModel);
            Assert.True(serializedModel.Contains(username));

            //password may not be contained depending
        }
コード例 #10
0
        public async Task <IActionResult> Register(AuthenticationRequestModel request)
        {
            var result = await _service.Register(request.UserName, request.Password);

            if (result.Success)
            {
                return(Ok(new AuthenticationRegistrationResponseModel()));
            }

            var responseError = new AuthenticationRegistrationResponseModel()
            {
                Errors  = result.Errors,
                Success = false
            };

            return(BadRequest(responseError));
        }
コード例 #11
0
        public static void Test_Can_JSON_Serialize_Then_Deserialize_With_Preserved_Values(string username, string password)
        {
            //arrange
            AuthenticationRequestModel authModel = new AuthenticationRequestModel(username, password);

            //act
            AuthenticationRequestModel deserializedModel =
                JsonConvert.DeserializeObject <AuthenticationRequestModel>(JsonConvert.SerializeObject(authModel));

            //assert
            Assert.NotNull(deserializedModel);
            Assert.NotNull(deserializedModel.UserName);
            Assert.NotNull(deserializedModel.Password);
            Assert.AreEqual(username, deserializedModel.UserName);

            //password may not be contained depending
        }
コード例 #12
0
        public IActionResult Authentication([FromBody] AuthenticationRequestModel authentication)
        {
            if (authentication.IsValid())
            {
                var response = _authAppService.Authentication(authentication);
                return(new ObjectResult(response)
                {
                    StatusCode = response.StatusCode()
                });
            }

            var badRequest = new BadRequestResponse("The fields E-mail/Cpf and Senha are required");

            return(new ObjectResult(badRequest)
            {
                StatusCode = badRequest.StatusCode()
            });
        }
コード例 #13
0
        public static AuthenticationRequestLogic Create(AuthenticationRequestModel model, AdaptersExtender adaptersExtender, CityLogic city)
        {
            switch (model.ParticipantType)
            {
            case ParticipantTypes.Driver:
                return(new DriverAuthenticationRequestLogic((DriverAuthenticationRequestModel)model, adaptersExtender, city));

                break;

            case ParticipantTypes.Pedestrian:
                return(new PedestrianAuthenticationRequestLogic((PedestrianAuthenticationRequestModel)model, adaptersExtender, city));

                break;

            default:
                throw new NotImplementedException();
                break;
            }
        }
コード例 #14
0
        public HttpResponseMessage GetToken(AuthenticationRequestModel authModel)
        {
            if (ModelState.IsValid)
            {

                string token = _securityService.Login(authModel);

                if (token != null)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, new TokenResponse {token = token});
                }

                return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User name or password is not valid");

            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Credentials provided are invalid");
            }
        }
コード例 #15
0
ファイル: CityLogic.cs プロジェクト: jaenudin86/TaxiOnline
        public ActionResult <ProfileLogic> Authenticate(AuthenticationRequestModel requestModel)
        {
            requestModel.DeviceId = _adaptersExtender.ServicesFactory.GetCurrentHardwareService().GetDeviceId();
            //ActionResult<MapPoint> locationResult = _adaptersExtender.ServicesFactory.GetCurrentHardwareService().GetCurrentLocation();
            //if (!locationResult.IsValid)
            //    return ActionResult<ProfileLogic>.GetErrorResult(new HardwareServiceException(HardwareServiceErrors.NoLocationService));
            if (!_interaction.CurrentLocation.HasValue)
            {
                return(ActionResult <ProfileLogic> .GetErrorResult(new HardwareServiceException(HardwareServiceErrors.NoLocationService)));
            }
            requestModel.CurrentLocation = _interaction.CurrentLocation.Value;
            AuthenticationRequestLogic  authenticationRequestLogic = AuthenticationRequestLogic.Create(requestModel, _adaptersExtender, this);
            ActionResult <ProfileLogic> result = authenticationRequestLogic.Authenticate();

            if (result.IsValid)
            {
                _interaction.CurrentProfile = result.Result;
            }
            return(result);
        }
コード例 #16
0
        public async Task <IActionResult> Login(AuthenticationRequestModel request)
        {
            var result = await _service.Login(request.UserName, request.Password);

            if (result.Success) //uspjesna prijava
            {
                var responseSuccess = new AuthenticationLoginReponseModel()
                {
                    Token = result.Token
                };

                return(Ok(responseSuccess));
            }

            var responseError = new AuthenticationLoginReponseModel()
            {
                Errors  = result.Errors,
                Success = false
            };

            return(BadRequest(responseError));
        }
コード例 #17
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticationRequestModel model)
        {
            User   user = null;
            string tokenString;
            string refreshToken;

            try
            {
                user = await UserService.AuthenticateAsync(model.Username, model.Password);

                if (user == null)
                {
                    return(BadRequest(new { message = "Username or password is incorrect" }));
                }

                tokenString  = AccessTokenService.GenerateAccessToken(user.Id.ToString());
                refreshToken = AccessTokenService.GenerateRefreshToken();
                await AccessTokenService.SaveRefreshTokenAsync(user.Id.ToString(), refreshToken);
            }
            catch (ArgumentException e)
            {
                return(BadRequest(e.Message));
            }
            catch
            {
                return(StatusCode(500));
            }

            return(Ok(new
            {
                id = user.Id,
                username = user.Username,
                token = tokenString,
                refreshToken = refreshToken
            }));
        }
コード例 #18
0
        private void RunAuthentication()
        {
            RadioButton pedestrianRadioButton  = FindViewById <RadioButton>(Resource.Id.pedestrianRadioButton);
            RadioButton driverRadioButton      = FindViewById <RadioButton>(Resource.Id.driverRadioButton);
            AuthenticationRequestModel request = null;// _model.CreateAuthenticationRequest(, null);

            if (pedestrianRadioButton.Checked)
            {
                request = _model.CreateAuthenticationRequest(ParticipantTypes.Pedestrian);
                FillPedestrianRequest((PedestrianAuthenticationRequestModel)request);
            }
            else if (driverRadioButton.Checked)
            {
                request = _model.CreateAuthenticationRequest(ParticipantTypes.Driver);
                FillDriverRequest((DriverAuthenticationRequestModel)request);
            }
            else
            {
                using (Toast errorToast = Toast.MakeText(Application.BaseContext, Resources.GetString(Resource.String.NoParticipationRole), ToastLength.Short))
                    errorToast.Show();
                return;
            }
            _model.BeginAuthenticate(request);
        }
コード例 #19
0
 public string Login(AuthenticationRequestModel authModel)
 {
     throw new NotImplementedException();
 }
コード例 #20
0
 public string GetTestValue([FromBody] AuthenticationRequestModel authenticationRequestModel)
 {
     return("Authorization is working");
 }
コード例 #21
0
        public async Task <IActionResult> GetTokenAsync(AuthenticationRequestModel model)
        {
            var result = await _loginService.GetTokenAsync(model);

            return(Ok(result));
        }
コード例 #22
0
        public string Login(AuthenticationRequestModel requestModel)
        {
            UserAuth userAuth = GetUserAuth(requestModel.Username);

            if (TestCryptoKey(requestModel.Password, new CryptoKey { Hash = userAuth.Password, Salt = userAuth.Salt }))
            {
                byte[] hToken = new byte[32];
                CryptProvider.GetBytes(hToken);
                string token = Convert.ToBase64String(hToken).Replace("=", "").Replace("+","").Replace("/","");

                if (SecurityRepository.SetUserToken(userAuth.id, token))
                {
                    return token;
                }
            }

            return null;
        }
コード例 #23
0
 public AuthenticationRequestLogic(AuthenticationRequestModel model, AdaptersExtender adaptersExtender, CityLogic city)
 {
     _model            = model;
     _adaptersExtender = adaptersExtender;
     _city             = city;
 }