Exemplo n.º 1
0
        public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid model"));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest("User does not exist"));
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

            if (!signInResult.Succeeded)
            {
                return(BadRequest("Invalid e-mail or password"));
            }

            var tokenKey = _config["Tokens:Key"];
            var issuer   = _config["Tokens:Issuer"];
            var audience = _config["Tokens:Audience"];

            var token = JwtTokenHelper.GenerateToken(user, tokenKey, issuer, audience);

            var result = new
            {
                token      = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo
            };

            return(Created(string.Empty, result));
        }
Exemplo n.º 2
0
        public async Task GenerateClientEndpoint(string userId, Claim[] claims, string appName)
        {
            var endpoints  = FakeEndpointUtils.GetFakeEndpoint(3).ToArray();
            var routerMock = new Mock <IEndpointRouter>();

            routerMock.SetupSequence(router => router.GetNegotiateEndpoint(null, endpoints))
            .Returns(endpoints[0])
            .Returns(endpoints[1])
            .Returns(endpoints[2]);
            var router   = routerMock.Object;
            var provider = new ServiceCollection().AddSignalRServiceManager()
                           .Configure <ServiceManagerOptions>(o =>
            {
                o.ApplicationName  = appName;
                o.ServiceEndpoints = endpoints;
            })
                           .AddSingleton(router).BuildServiceProvider();
            var negotiateProcessor = provider.GetRequiredService <NegotiateProcessor>();

            for (int i = 0; i < 3; i++)
            {
                var negotiationResponse = await negotiateProcessor.NegotiateAsync(HubName, null, userId, claims, _tokenLifeTime);

                var tokenString = negotiationResponse.AccessToken;
                var token       = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString);

                string expectedToken = JwtTokenHelper.GenerateJwtBearer(ClientEndpointUtils.GetExpectedClientEndpoint(HubName, appName, endpoints[i].Endpoint), ClaimsUtility.BuildJwtClaims(null, userId, () => claims), token.ValidTo, token.ValidFrom, token.ValidFrom, endpoints[i].AccessKey);

                Assert.Equal(ClientEndpointUtils.GetExpectedClientEndpoint(HubName, appName, endpoints[i].Endpoint), negotiationResponse.Url);
                Assert.Equal(expectedToken, tokenString);
            }
        }
Exemplo n.º 3
0
        public BaseResponse <bool> IsAllowedToken(string token)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(BaseResponse <bool> .BadRequest());
                }

                var authModel = JwtTokenHelper.DecodeJwtToken(token);
                if (authModel != null)
                {
                    var user = Find(authModel.Email);
                    if (user != null)
                    {
                        var tokenEffectiveDate = long.Parse(authModel.TokenEffectiveTimeStick);
                        var userEffectiveDate  = user.TokenEffectiveTimeStick;
                        if (tokenEffectiveDate > userEffectiveDate)
                        {
                            return(BaseResponse <bool> .Success(true));
                        }
                        return(BaseResponse <bool> .BadRequest(message : "Token is not allowed because user was signed out."));
                    }
                }

                return(BaseResponse <bool> .BadRequest());
            }
            catch (Exception ex)
            {
                return(BaseResponse <bool> .InternalServerError(message : ex.Message, fullMsg : ex.StackTrace));
            }
        }
Exemplo n.º 4
0
        public async Task Call_NegotiateAsync_After_WithEndpoints(ServiceTransportType serviceTransportType)
        {
            var serviceManager = new ServiceManagerBuilder()
                                 .WithOptions(o =>
            {
                o.ServiceTransportType = serviceTransportType;
                o.ServiceEndpoints     = ServiceEndpoints;
            })
                                 .BuildServiceManager();
            var hubContext = await serviceManager.CreateHubContextAsync(Hub, default);

            for (var i = 0; i < 5; i++)
            {
                var randomEndpoint      = ServiceEndpoints[StaticRandom.Next(0, Count)];
                var negotiationResponse = await(hubContext as IInternalServiceHubContext)
                                          .WithEndpoints(new ServiceEndpoint[] { randomEndpoint })
                                          .NegotiateAsync();

                Assert.Equal(ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint), negotiationResponse.Url);
                var tokenString   = negotiationResponse.AccessToken;
                var token         = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString);
                var expectedToken = JwtTokenHelper.GenerateJwtBearer(
                    ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint),
                    ClaimsUtility.BuildJwtClaims(null, null, null), token.ValidTo, token.ValidFrom, token.ValidFrom, randomEndpoint.AccessKey);
                Assert.Equal(expectedToken, tokenString);
            }
        }
Exemplo n.º 5
0
        public async Task <BaseResponse <bool> > SingleSignInAsync(HttpContext httpContext, AuthenticateViewModel model, string authenticationScheme = "", AuthenticationProperties authenticationProperties = null)
        {
            try
            {
                if (model == null)
                {
                    return(BaseResponse <bool> .BadRequest());
                }
                authenticationScheme     = (string.IsNullOrEmpty(authenticationScheme)) ? SSOAuthenticationScheme : authenticationScheme;
                authenticationProperties = authenticationProperties == null ? new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(365)
                } : authenticationProperties;
                var claims         = JwtTokenHelper.GetUserClaims(model);
                var claimsIdentity = new ClaimsIdentity(claims, authenticationScheme);
                var user           = new ClaimsPrincipal(claimsIdentity);
                await httpContext.SignInAsync(authenticationScheme, user, authenticationProperties);

                return(BaseResponse <bool> .Success(true));
            }
            catch (Exception e)
            {
                return(BaseResponse <bool> .InternalServerError(message : e.Message, fullMsg : e.StackTrace));
            }
        }
Exemplo n.º 6
0
    public override async Task <GrpcResponse> Login(LoginRequest request, ServerCallContext context)
    {
        var loginDto    = _mapper.Map <UserLoginDto>(request);
        var loginResult = await _accountService.LoginAsync(loginDto);

        var grpcResponse = new GrpcResponse()
        {
            IsSuccessStatusCode = loginResult.IsSuccess
        };

        if (!grpcResponse.IsSuccessStatusCode)
        {
            grpcResponse.Error = loginResult.ProblemDetails?.Detail;
            return(grpcResponse);
        }

        var validatedInfo = loginResult.Content;
        var loginReply    = new LoginReply
        {
            Token        = JwtTokenHelper.CreateAccessToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.Account, validatedInfo.Id.ToString(), validatedInfo.Name, validatedInfo.RoleIds).Token,
            RefreshToken = JwtTokenHelper.CreateRefreshToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.Id.ToString()).Token
        };

        grpcResponse.Content = Any.Pack(loginReply);
        return(grpcResponse);
    }
Exemplo n.º 7
0
        public void BatchSendCouponsByUserEmailsAsync(IList <string> emails, CouponDto coupon)
        {
            foreach (var email in emails)
            {
                // step 1: Create payloads: user email, coupon ID
                IList <object> payloads = new List <object>()
                {
                    "emails", coupon.Id.ToString()
                };

                // Step 2: Generate email confirm token
                var    token     = JwtTokenHelper.GenerateToken(payloads, coupon.EndTimeUTC, _tokenConfig.Key);
                string tokenHtml = HttpUtility.UrlEncode(token);

                // Step 3: Generate email data
                var from = _emailConfigs.SenderGeneral;
                var tos  = new List <string>()
                {
                    email
                };
                var ccs         = new List <string>();
                var subject     = "Course Studio New Coupon Is Coming";
                var confirmUrl  = _emailConfigs.CouponRedeemUrl + "?userId=" + email + "&coupon=" + coupon.Id + "&token=" + tokenHtml;
                var HtmlContent = "<p>Course Studio new coupon is comingwer</p><br>" + confirmUrl;

                // Step 4: send email
                // TODO: shouldn't use the ASYNC method
                SendAsync(from, tos.ToArray(), ccs.ToArray(), subject, HtmlContent);
            }
        }
Exemplo n.º 8
0
        //For AQ Account
        private AuthenticateViewModel GetAuthResponseModel(Users user)
        {
            try
            {
                if (user == null)
                {
                    return(null);
                }
                var authModel    = _mapper.Map <Users, AuthenticateViewModel>(user);
                var refreshToken = UniqueIDHelper.GenarateRandomString(12);
                user.RefreshToken = refreshToken;
                var saveSucceed = _accountService.UpdateUser(user).IsSuccessStatusCode;
                if (saveSucceed)
                {
                    authModel.RefreshToken            = refreshToken;
                    authModel.TokenEffectiveDate      = DateTime.Now.ToString();
                    authModel.TokenEffectiveTimeStick = DateTime.Now.Ticks.ToString();
                    authModel.AccountTypeFid          = ((int)AccountTypeEnum.Admin).ToString();
                    var result = JwtTokenHelper.GenerateJwtTokenModel(authModel, TOKEN_MINUTE_TIME_LIFE);
                    return(result);
                }

                return(null);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 9
0
 public static void AddAppSetting(this IServiceCollection services, IConfiguration configuration)
 {
     DependencyInjectionHelper.Init(ref services);
     JwtTokenHelper.Init(configuration);
     services.AddOptions();
     services.Configure <ApiServer>(configuration.GetSection("ApiServer"));
 }
Exemplo n.º 10
0
        public async Task <ActionResult <LoginResult> > Login([FromForm] LoginDto loginModel)
        {
            _logger.Log(LogLevel.Warning, "Received login request");
            var password = EncryptHelper.DecryptWithAES(loginModel.Password);
            var result   = await _signInManager
                           .PasswordSignInAsync(loginModel.Username, password, loginModel.RememberMe, false);

            if (!result.Succeeded)
            {
                return(Unauthorized(new LoginResult {
                    Success = false, Error = "Failed to login"
                }));
            }

            var user = await _userManager.FindByNameAsync(loginModel.Username);

            var roles = await _userManager.GetRolesAsync(user);

            var config = _configuration.GetSection("JwtConfig");

            await _userStates.SetLoginAsync(loginModel.Username);

            var token = JwtTokenHelper.IssueJwtToken(user.UserName, roles.ToList(), config);

            _logger.LogInformation("Login successful");
            return(Ok(new LoginResult {
                Success = true, Token = token
            }));
        }
Exemplo n.º 11
0
 public UsersController(IConfiguration configuration, IdeaPoolContext dbContext, JwtTokenHelper tokenHelper, ILogger <UsersController> logger)
 {
     this.configuration = configuration;
     this.dbContext     = dbContext;
     this.tokenHelper   = tokenHelper;
     this.logger        = logger;
 }
Exemplo n.º 12
0
        internal void GenerateClientAccessTokenTest()
        {
            var endpoint             = "https://abc";
            var accessKey            = "nOu3jXsHnsO5urMumc87M9skQbUWuQ+PE5IvSUEic8w=";
            var testConnectionString = $"Endpoint={endpoint};AccessKey={accessKey};Version=1.0;";
            var userId           = "UserA";
            var hubName          = "signalrbench";
            var expectedAudience = $"{endpoint}/client/?hub={hubName.ToLower()}";
            var lifeTime         = TimeSpan.FromSeconds(99);
            var claims           = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, userId), new Claim("type1", "val1")
            };

            var serviceManagerOptions = new ServiceManagerOptions
            {
                ConnectionString     = testConnectionString,
                ServiceTransportType = ServiceTransportType.Transient
            };
            var serviceManager = new ServiceManager(serviceManagerOptions);
            var tokenString    = serviceManager.GenerateClientAccessToken(hubName, claims, lifeTime);
            var token          = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString);
            var customClaims   = new Claim[] { new Claim("type1", "val1") };

            string expectedToken = JwtTokenHelper.GenerateExpectedAccessToken(token, expectedAudience, accessKey, customClaims);

            Assert.Equal(expectedToken, tokenString);
        }
Exemplo n.º 13
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpStatusCode statusCode;
            string         token;

            //determine whether a jwt exists or not
            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
                return(base.SendAsync(request, cancellationToken));
            }

            try
            {
                SecurityToken           securityToken;
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                var validationParameters        = JwtTokenHelper.GetTokenValidationParameters(Settings.JwtSecretKey);
                //extract and assign the user of the jwt
                Thread.CurrentPrincipal  = handler.ValidateToken(token, validationParameters, out securityToken);
                HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);

                return(base.SendAsync(request, cancellationToken));
            }
            catch (SecurityTokenValidationException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (Exception)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }
            return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode) { }));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Login(LoginModel loginModel)
        {
            _logger.LogInformation("Started : Logging In.");
            UserDto userDto = await _userService.AuthenticateUser(loginModel.UserName, loginModel.Password);

            if (userDto != null)
            {
                // On Successful authentication, generate jwt token.
                string token = JwtTokenHelper.GenerateJwtToken(userDto, _appSettings);

                return(Ok(
                           new ApiResponse <string>
                {
                    IsSuccess = true,
                    Result = token,
                    Message = "Authentication successful."
                }));
            }
            else
            {
                return(BadRequest(
                           new ApiResponse <string>
                {
                    IsSuccess = false,
                    Result = "Authentication failed.",
                    Message = "Username or password is incorrect."
                }));
            }
        }
Exemplo n.º 15
0
        public IActionResult Create([FromBody] UserCreateModel createModel)
        {
            var userId = JwtTokenHelper.GetSignInProfile(User).UserId;
            var result = _accountService.Resigster(createModel, userId);

            return(Ok(result));
        }
        public IHttpActionResult PostPaRequestNotes(PaRequestNote paRequestNote)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var headers = Request.Headers;

            if (headers.Contains("token"))
            {
                var userToken = headers.GetValues("token").First();

                string userName = JwtTokenHelper.GetTokenPayloadValue(userToken, "unique_name");
                paRequestNote.Created        = DateTime.Now;
                paRequestNote.CreatedBy      = userName;
                paRequestNote.LastModified   = DateTime.Now;
                paRequestNote.LastModifiedBy = userName;

                db.PaRequestNotes.Add(paRequestNote);
                db.SaveChanges();
            }

            return(CreatedAtRoute("DefaultApi", new { id = paRequestNote.Id }, paRequestNote));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncInitializationMiddleware"/> class.
        /// </summary>
        /// <param name="next">The next middleware.</param>
        /// <param name="jwtTokenHelper">The JWT token helper.</param>
        /// <param name="awsCognitoClientSecretHelper">The AWS Cognito Client Secret Helper.</param>
        /// <param name="lifetime">The application lifetime.</param>
        /// <param name="awsCognitoHelper">The AWS Cognito Helper.</param>
        /// <param name="configSettings">The Config Settings.</param>
        /// <param name="logger">Logger</param>
        public AsyncInitializationMiddleware(RequestDelegate next,
                                             IHostApplicationLifetime lifetime,
                                             AWSCognitoHelper awsCognitoHelper,
                                             JwtTokenHelper jwtTokenHelper,
                                             AWSCognitoClientSecretHelper awsCognitoClientSecretHelper,
                                             IOptions <ConfigSettings> configSettings,
                                             ILogger <AsyncInitializationMiddleware> logger
                                             )
        {
            this._next                         = next;
            this._awsCognitoHelper             = awsCognitoHelper;
            this._awsCognitoClientSecretHelper = awsCognitoClientSecretHelper;
            this._configSettings               = configSettings.Value;
            this._jwtTokenHelper               = jwtTokenHelper;
            this._logger                       = logger;

            // Start initialization when the app starts
            var startRegistration = default(CancellationTokenRegistration);
            var registration      = startRegistration;

            lifetime.ApplicationStarted.Register(() =>
            {
                _initializationTask = InitializeAsync(lifetime.ApplicationStopping);
                registration.Dispose();
            });
        }
Exemplo n.º 18
0
        public ActionResult <object> Get(string username, string password)
        {
            Managers managerModel        = _manager.Login(username, password);
            var      jwtSection          = _configuration.GetSection("jwt");
            int      tokenExpires        = Convert.ToInt32(jwtSection.GetSection("TokenExpires").Value);
            int      refreshTokenExpires = Convert.ToInt32(jwtSection.GetSection("RefreshTokenExpires").Value);

            if (managerModel == null)
            {
                return(ErrorResult <int>("用户名或密码错误"));
            }

            JwtTokenHelper jwtTokenHelper = new JwtTokenHelper();

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, managerModel.UserName),
                new Claim(ClaimTypes.Role, managerModel.RoleId.ToString()),
                new Claim(JwtRegisteredClaimNames.Sid, managerModel.Id.ToString()),
            };

            string token               = jwtTokenHelper.GetToken(claims);
            string refreshToken        = jwtTokenHelper.RefreshToken();
            string tokenExpired        = StringHelper.GetTimeStamp(DateTime.UtcNow.AddMinutes(tokenExpires));
            string refreshToeknExpired = StringHelper.GetTimeStamp(DateTime.UtcNow.AddMinutes(refreshTokenExpires));

            _manager.AddRefeshToken(token, refreshToken, managerModel.Id, refreshTokenExpires);

            return(SuccessResult <object>(new { token = token, refreshToken = refreshToken, userName = managerModel.UserName, expires = tokenExpired, refreshExpires = refreshToeknExpired }));
        }
Exemplo n.º 19
0
        private string RefreshToken(UserLogin userAccount, User userDetails)
        {
            var        refreshId = DateTime.Now.Ticks; // To verify freshness of issued Token.
            JwtPayload payload   = new JwtPayload();

            payload.Add("isAdmin", userAccount.IsAdmin);
            payload.Add("userLoginId", userAccount.Id);
            payload.Add("displayName", userDetails.FirstName + " " + userDetails.LastName);
            payload.Add("refreshId", refreshId);

            var token = JwtTokenHelper.GenerateJwtToken(userAccount.Login,
                                                        userDetails.Role.Name, payload);

            userAccount.AccessFailedCount = 0;
            userAccount.LockoutEnabled    = false;
            userAccount.LockoutEnd        = DateTime.Parse("1/1/1900");
            userAccount.RefreshId         = refreshId;
            userAccount.LastModifiedBy    = "SECURITY";
            userAccount.LastModified      = DateTime.Now;
            db.Entry(userAccount).State   = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(token);
        }
Exemplo n.º 20
0
        public void GenerateJwtToken_Should_Return_Null_With_Missing_Or_Empty_JwtSettings_Info(IJwtSettings settings)
        {
            JwtTokenHelper helper = new JwtTokenHelper(settings);
            var            token  = helper.GenerateJwtToken(sampleUser);

            Assert.Null(token);
        }
Exemplo n.º 21
0
        protected async Task <IActionResult> GenerateJWTToken(TUser user)
        {
            var rolesAndScopes = await AuthenticationHelper.GetRolesAndScopesAsync(user, _userManager, _roleManager);

            var roles  = rolesAndScopes.Roles;
            var scopes = rolesAndScopes.Scopes;

            if (!string.IsNullOrWhiteSpace(_privateSigningKeyPath))
            {
                var key     = SigningKey.LoadPrivateRsaSigningKey(_privateSigningKeyPath);
                var results = JwtTokenHelper.CreateJwtTokenSigningWithRsaSecurityKey(user.Id, user.UserName, user.Email, roles, _tokenExpiryMinutes, key, _localIssuer, _audience, scopes.ToArray());
                return(Created("", results));
            }
            else if (!string.IsNullOrWhiteSpace(_privateSigningCertificatePassword))
            {
                var key     = SigningKey.LoadPrivateSigningCertificate(_privateSigningCertificatePath, _privateSigningCertificatePassword);
                var results = JwtTokenHelper.CreateJwtTokenSigningWithCertificateSecurityKey(user.Id, user.UserName, user.Email, roles, _tokenExpiryMinutes, key, _localIssuer, _audience, scopes.ToArray());
                return(Created("", results));
            }
            else
            {
                var key     = SigningKey.LoadSymmetricSecurityKey(_privateSymmetricKey);
                var results = JwtTokenHelper.CreateJwtTokenSigningWithKey(user.Id, user.UserName, user.Email, roles, _tokenExpiryMinutes, key, _localIssuer, _audience, scopes.ToArray());
                return(Created("", results));
            }
        }
Exemplo n.º 22
0
        public void GenerateJwtToken_Should_Return_Not_Null_Token()
        {
            JwtTokenHelper helper = new JwtTokenHelper(new JwtSettingsFake());
            var            token  = helper.GenerateJwtToken(sampleUser);

            Assert.NotNull(token);
        }
Exemplo n.º 23
0
 public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
 {
     if (this._userContext.TokenExpiry != null)
     {
         DateTime tokenExpiresOn = Convert.ToDateTime(this._userContext.TokenExpiry);
         if (DateTime.Now.AddMinutes(15) > tokenExpiresOn)
         {
             // Generate new token
             try
             {
                 if (string.IsNullOrEmpty(actionExecutedContext.HttpContext.Response.Headers["RefreshToken"]))
                 {
                     var token = JwtTokenHelper.GenerateJSONWebToken(
                         this._jwtIssuerOptions,
                         this._userContext.UserInfo.Id,
                         this._userContext.UserInfo.Email,
                         this._userContext.SessionId);
                     actionExecutedContext.HttpContext.Response.Headers.Add("RefreshToken", token);
                 }
             }
             catch (Exception)
             {
                 // throw;
             }
         }
     }
 }
Exemplo n.º 24
0
        public void GenerateJwtToken_Should_Return_Token_With_Correct_Info()
        {
            var jwtSettings = new JwtSettingsFake();
            var helper      = new JwtTokenHelper(jwtSettings);
            var token       = helper.GenerateJwtToken(sampleUser);

            var tokenHandler = new JwtSecurityTokenHandler();

            var tokenValidationParams = new TokenValidationParameters()
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = jwtSettings.Issuer,
                ValidAudience    = jwtSettings.Issuer,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.TokenSecret))
            };

            SecurityToken validatedToken;

            var claims = tokenHandler.ValidateToken(token, tokenValidationParams, out validatedToken);

            Assert.True(claims.Identity.IsAuthenticated);
        }
        /// <summary>
        /// Method for Host Login Access
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task <bool> HostLoginAccess(string email, string password)
        {
            //checking null Object
            if (email == null && password == null)
            {
                throw new NullReferenceException("host");
            }

            //checking null fields
            if (email == null || password == null)
            {
                throw new UserDoesNotExistException("Email or password cannot be null");
            }


            string hashedPassword = await _repositoryUtility.IsValidHostLogin(email);

            if (hashedPassword == null)
            {
                throw new UserDoesNotExistException("Email not registered for host");
            }
            bool isSame = _userUtilityHelper.CheckPassword(password, hashedPassword);

            if (isSame == true)
            {
                //code to generate access token
                JwtTokenHelper tokenobj    = new JwtTokenHelper();
                string         tokenString = tokenobj.GenerateToken(email, "host");
            }
            return(await Task.FromResult(isSame));
        }
Exemplo n.º 26
0
        public IActionResult SignOutAllDevices()
        {
            var key    = JwtTokenHelper.GetClaimValue(User, ClaimConstant.Email) ?? string.Empty;
            var result = _signInService.SignOutAllDevice(key);

            return(Ok(result));
        }
Exemplo n.º 27
0
        public BaseResponse <string> Create(string token, string returnUrl)
        {
            try
            {
                if (string.IsNullOrEmpty(token) || JwtTokenHelper.DecodeJwtToken(token) == null)
                {
                    return(BaseResponse <string> .BadRequest());
                }

                var authModel = JwtTokenHelper.DecodeJwtToken(token);
                var userToken = new UserTokens()
                {
                    Id          = UniqueIDHelper.GenarateRandomString(12),
                    UserFid     = Guid.Parse(authModel.UserId),
                    AccessToken = token,
                    ReturnUrl   = returnUrl,
                };
                _db.UserTokens.Add(userToken);
                if (_db.SaveChanges() > 0)
                {
                    return(BaseResponse <string> .Success(userToken.Id));
                }
                return(BaseResponse <string> .BadRequest());
            }
            catch (Exception ex)
            {
                return(BaseResponse <string> .InternalServerError(message : ex.Message, fullMsg : ex.StackTrace));
            }
        }
Exemplo n.º 28
0
    public async Task <ActionResult <UserTokenInfoDto> > RefreshAccessTokenAsync([FromBody] UserRefreshTokenDto input)
    {
        var claimOfId = JwtTokenHelper.GetClaimFromRefeshToken(_jwtOptions.Value, input.RefreshToken, JwtRegisteredClaimNames.NameId);

        if (claimOfId is not null)
        {
            var id = claimOfId.Value.ToLong();
            if (id is null)
            {
                return(Forbid());
            }

            var validatedInfo = await _accountService.GetUserValidatedInfoAsync(id.Value);

            if (validatedInfo is null)
            {
                return(Forbid());
            }

            var jti = JwtTokenHelper.GetClaimFromRefeshToken(_jwtOptions.Value, input.RefreshToken, JwtRegisteredClaimNames.Jti);
            if (jti.Value != validatedInfo.ValidationVersion)
            {
                return(Forbid());
            }

            var accessToken  = JwtTokenHelper.CreateAccessToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.Account, validatedInfo.Id.ToString(), validatedInfo.Name, validatedInfo.RoleIds);
            var refreshToken = JwtTokenHelper.CreateRefreshToken(_jwtOptions.Value, validatedInfo.ValidationVersion, validatedInfo.Id.ToString());

            await _accountService.ChangeUserValidateInfoExpiresDtAsync(id.Value);

            var tokenInfo = new UserTokenInfoDto(accessToken.Token, accessToken.Expire, refreshToken.Token, refreshToken.Expire);
            return(Ok(tokenInfo));
        }
        return(Forbid());
    }
        public LoginResponse Login([FromBody] LoginRequest login)
        {
            if (login == null)
            {
                throw new ArgumentNullException(nameof(login));
            }

            connectionFactory = ConnectionHelper.GetConnection();
            var context = new DbContext(connectionFactory);

            var userRep = new UserRepository(context);
            var user    = userRep.LoginUser(login.Username, login.Password);

            // if credentials are valid
            if (user != null)
            {
                string token = JwtTokenHelper.GenerateToken(user.UserId.ToString(), user.UserName, user.FirstName, user.LastName);

                //return the token
                return(new LoginResponse
                {
                    Token = token
                });
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Incorrect Username or Password."));
            }
        }
Exemplo n.º 30
0
        public BaseResponse <AuthenticateViewModel> AuthenticateByToken(string accessToken)
        {
            try
            {
                if (string.IsNullOrEmpty(accessToken))
                {
                    return(BaseResponse <AuthenticateViewModel> .BadRequest());
                }

                var authModel = JwtTokenHelper.DecodeJwtToken(accessToken);
                if (authModel != null && !string.IsNullOrEmpty(authModel.Email))
                {
                    var user = LoadRelated(FindByEmail(authModel.Email));
                    if (user == null)
                    {
                        return(BaseResponse <AuthenticateViewModel> .NotFound());
                    }
                    if (IsNotDeleted(user) && IsActivated(user))
                    {
                        var authResponseModel = GetAuthResponseModel(user);
                        if (authResponseModel != null)
                        {
                            return(BaseResponse <AuthenticateViewModel> .Success(authResponseModel));
                        }
                    }
                }

                return(BaseResponse <AuthenticateViewModel> .BadRequest());
            }
            catch (Exception ex)
            {
                return(BaseResponse <AuthenticateViewModel> .InternalServerError(message : ex.Message, fullMsg : ex.StackTrace));
            }
        }