public static string GenerateToken(TokenRequestModel model)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, model.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(model.Key));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(model.Issuer,                         // issued by
                                             model.Audience,                       // issued for
                                             claims,                               // payload
                                             expires: DateTime.Now.AddMinutes(30), // valid for
                                             signingCredentials: creds);           // signature

            var tokenEncoded = new JwtSecurityTokenHandler().WriteToken(token);

            return(tokenEncoded);
        }
Beispiel #2
0
        public IHttpActionResult TokenResquest(TokenRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            PayResponseBindingModel pr = new PayResponseBindingModel()
            {
                msgId  = 7,
                tid    = model.tid,
                token  = "0",
                status = 1
            };


            notificationService.TokenRequest(Global.NotificationHubPNS.APNS, model);

            pr.status = 0;
            return(Ok(pr));
        }
Beispiel #3
0
        public HttpResponseMessage Post([FromBody] TokenRequestModel model)
        {
            try
            {
                var developer = Repository.GetApiUsers().FirstOrDefault(u => u.AppId == model.ApiKey);
                if (developer != null)
                {
                    var secret    = developer.Secret;
                    var key       = Convert.FromBase64String(secret);
                    var provider  = new System.Security.Cryptography.HMACSHA256(key);
                    var hash      = provider.ComputeHash(Encoding.UTF8.GetBytes(developer.AppId));
                    var signature = Convert.ToBase64String(hash);

                    if (model.Signature == signature)
                    {
                        var rawTokenInfo = $"{developer.AppId} {DateTime.UtcNow:d}";
                        var rawTokenByte = Encoding.UTF8.GetBytes(rawTokenInfo);
                        var token        = provider.ComputeHash(rawTokenByte);

                        var authToken = new AuthToken
                        {
                            Token      = Convert.ToBase64String(token),
                            Expiration = DateTime.UtcNow.AddDays(7),
                            ApiUser    = developer
                        };

                        if (Repository.Insert(authToken) && Repository.SaveAll())
                        {
                            return(Request.CreateResponse(HttpStatusCode.Created, ModelFactory.Create(authToken)));
                        }
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (Exception xc)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, xc));
            }
        }
Beispiel #4
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            try
            {
                var salt = Guid.NewGuid().ToString();
                var user = new User {
                    UserName = model.Email, Email = model.Email, PhoneNumber = model.Phone, HashSalt = salt
                };

                var password = $"{model.Password + salt}";
                var result   = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    var token = await GetToken(user);

                    var response = new TokenRequestModel
                    {
                        Status  = "success",
                        Message = "acount successfully created",
                        Token   = new JwtSecurityTokenHandler().WriteToken(token),
                        Expires = token.ValidTo,
                    };
                    return(Created("", response));
                }
                return(BadRequest(new ErrorModel {
                    Status = "error", Message = $"cannot register user {model.Email}"
                }));
            }
            catch (Exception ex)
            {
                var response = new ErrorModel
                {
                    Status  = "error",
                    Message = $"{ex.Message}",
                };
                return(BadRequest(response));
            }
        }
        // These method will be called by Client or application Users => Angular/REST API app
        public async Task <TokenResponseModel> Auth(TokenRequestModel model)
        {
            // We will return Generic 500 HTTP Server Status Error
            // If we receive an invalid payload
            if (model == null)
            {
                return(CreateErrorResponseToken("Model State is Invalid", HttpStatusCode.InternalServerError));
            }

            switch (model.GrantType)
            {
            case "password":
                return(await GenerateNewToken(model));

            case "refresh_token":
                return(await RefreshToken(model));

            default:
                // not supported - return a HTTP 401 (Unauthorized)
                return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
            }
        }
        public async Task <AuthModel> GetTokenAsync(TokenRequestModel model)
        {
            var authModel = new AuthModel();
            var user      = await _userManager.FindByEmailAsync(model.Email);

            if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password))
            {
                authModel.Message = "Email Or Password InCorrect";
                return(authModel);
            }
            var jwtSecurityToken = await CreateJwtToken(user);

            var RolesList = await _userManager.GetRolesAsync(user);

            authModel.IsAuthenticated = true;
            authModel.Email           = user.Email;
            authModel.Token           = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            authModel.UserName        = user.UserName;
            authModel.ExpiresOn       = jwtSecurityToken.ValidTo;
            authModel.Roles           = RolesList.ToList();
            return(authModel);
        }
        public HttpResponseMessage Post([FromBody] TokenRequestModel model)
        {
            try
            {
                var user = TheRepository.GetApiUsers().Where(u => u.AppId == model.ApiKey).FirstOrDefault();
                if (user != null)
                {
                    var secret = user.Secret;
                    var key    = Convert.FromBase64String(secret);

                    HMACSHA256 provider  = new HMACSHA256(key);
                    byte[]     hash      = provider.ComputeHash(Encoding.UTF8.GetBytes(user.AppId));
                    string     signature = Convert.ToBase64String(hash);

                    if (signature == model.Signature)
                    {
                        var rawTokenInfo = string.Concat(user.AppId + DateTime.UtcNow.ToString("d"));
                        var rawTokenByte = Encoding.UTF8.GetBytes(rawTokenInfo);
                        var token        = provider.ComputeHash(rawTokenByte);
                        var authToken    = new AuthToken()
                        {
                            Token      = Convert.ToBase64String(token),
                            Expiration = DateTime.UtcNow.AddDays(7),
                            ApiUser    = user
                        };
                        if (TheRepository.Insert(authToken) && TheRepository.SaveAll())
                        {
                            return(Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(authToken)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest));
        }
Beispiel #8
0
        public async Task <IActionResult> Auth([FromBody] TokenRequestModel model) // granttype = "refresh_token"
        {
            // We will return Generic 500 HTTP Server Status Error
            // If we receive an invalid payload
            if (model == null)
            {
                return(new StatusCodeResult(500));
            }

            switch (model.GrantType)
            {
            case "password":
                return(await GenerateNewToken(model));

            case "refresh_token":
                return(await RefreshToken(model));

            default:
                // not supported - return a HTTP 401 (Unauthorized)
                return(new UnauthorizedResult());
            }
        }
        public IHttpActionResult TestNotification(TokenRequestModel model)
        {
            string slog = string.Format("TestNotification tokenReqModel: {0}", JsonConvert.SerializeObject(model));

            logger.Debug(slog);

            HttpStatusCode ret = HttpStatusCode.InternalServerError;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = userService.GetUserByEmail(model.vid);

            if (user != null)
            {
                try
                {
                    ///////////////////////////////////////
                    // Notify the mobile applet
                    ///////////////////////////////////////
                    notificationService.TokenRequest(Global.NotificationHubPNS.APNS, user.Id, model);
                }
                catch (MessagingException e)
                {
                    ReturnGoneIfHubResponseIsGone(e);
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.Message));
                }
            }
            else
            {
                return(BadRequest("Bad UserId"));
            }
            return(Ok(ret));
        }
Beispiel #10
0
        /// <summary>
        /// Method to Refresh JWT and Refresh Token.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private async Task <IActionResult> RefreshToken(TokenRequestModel model)
        {
            try
            {
                var rt = _db.RefreshTokens.FirstOrDefault(t =>
                                                          t.ClientId == _appSettings.ClientId &&
                                                          t.Value == model.RefreshToken);

                if (rt == null || rt.ExpiryTime < DateTime.UtcNow)
                {
                    return(new UnauthorizedResult());
                }

                //Check if there`s user with the refresh token`s userId
                var user = await _userManager.FindByIdAsync(rt.UserId);

                if (user == null)
                {
                    return(new UnauthorizedResult());
                }

                //Generate new Refresh token
                var rtNew = _tokenCreator.CreateRefreshToken(rt.ClientId, rt.UserId);

                _db.RefreshTokens.Remove(rt);
                _db.RefreshTokens.Add(rtNew);
                await _db.SaveChangesAsync();


                var response = await _tokenCreator.CreateAccessToken(user, rtNew.Value);

                return(Ok(new { authToken = response }));
            }
            catch (Exception e)
            {
                return(new UnauthorizedResult());
            }
        }
Beispiel #11
0
        public async Task <AuthenticationModel> LoginAsync(TokenRequestModel model)
        {
            var authenticationModel = new AuthenticationModel();
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                authenticationModel.IsAuthenticated = false;
                authenticationModel.Message         = $"No Accounts Registered with {model.Email}";
                return(authenticationModel);
            }

            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                authenticationModel.IsAuthenticated = true;
                authenticationModel.Email           = user.Email;
                authenticationModel.Name            = user.Name;
                return(authenticationModel);
            }
            authenticationModel.IsAuthenticated = false;
            authenticationModel.Message         = $"Incorrect Credentials for user {user.Email}";
            return(authenticationModel);
        }
Beispiel #12
0
        public async Task <IActionResult> Auth([FromBody] TokenRequestModel model)
        {
            //We will return Generic 500 Http Server Error
            //If we receive an invalid payload

            if (model == null)
            {
                return(new StatusCodeResult(500));
            }

            switch (model.GrantType)
            {
            case GrantType.Login:
                return(await GenerateNewToken(model));

            case GrantType.RefreshToken:
                return(await RefreshToken(model));

            default:
                // Non supported return 401(Unauthorized)
                return(new UnauthorizedResult());
            }
        }
Beispiel #13
0
        public IActionResult Request(TokenRequestModel model)
        {
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, "管理员")
                , new Claim(ClaimTypes.Role, "admin")
            };


            var expires = DateTime.Now.AddDays(Convert.ToDouble(configuration["JwtSettings:ExpiresDay"]));
            var token   = new JwtSecurityToken(
                issuer: configuration["JwtSettings:Issuer"],
                audience: configuration["JwtSettings:Audience"],
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: creds);

            return(Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token), Expires = expires.ToString("yyyy-MM-dd HH:mm:ss") }));
        }
Beispiel #14
0
        public IActionResult Post(TokenRequestModel tokenRequest)
        {
            if (tokenRequest != null && !string.IsNullOrEmpty(tokenRequest.ApiKey))
            {
                var user = _IMerchantService.GetMerchantProfile(tokenRequest.ApiKey);

                if (user != null)
                {
                    //create claims details based on the user information
                    var claims = new[] {
                        new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
                        new Claim("ProfileId", user.Id.ToString()),
                        new Claim("Name", user.Name),
                        new Claim("UserName", user.Merchant.Email),
                        new Claim("APIMode", user.Mode == Core.Models.Common.APIMode.Live ? "1" :"0")
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

                    var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddMinutes(10), signingCredentials: signIn);

                    return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
                }
                else
                {
                    return(BadRequest("Invalid credentials"));
                }
            }
            else
            {
                return(BadRequest());
            }
        }
Beispiel #15
0
        //Method to Refresh JWT and Refresh Token
        private async Task <TokenResponseModel> RefreshToken(TokenRequestModel model)
        {
            TokenModel rt = await _dalLayer.GetRefreshToken(_appSettings.ClientId, model.RefreshToken.ToString());

            // check if refresh token is expired
            if (rt.ExpiryTime < DateTime.UtcNow)
            {
                return(null);
            }

            // check if there's an user with the refresh token's userId
            var user = await _userManager.FindById(rt.UserId);

            if (user == null)
            {
                // UserId not found or invalid
                return(null);
            }

            // generate a new refresh token
            var rtNew = CreateRefreshToken(rt.ClientId, rt.UserId);

            // invalidate the old refresh token (by deleting it)
            List <TokenModel> rtList = new List <TokenModel>()
            {
                rt
            };
            await _dalLayer.RemoveTokens(rtList);

            // add the new refresh token
            await _dalLayer.AddToken(rtNew);

            //
            var response = await CreateAccessToken(user, rtNew.Value);

            return(response);
        }
Beispiel #16
0
        public async Task <IActionResult> Auth([FromBody] TokenRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                var jwtToken = await _authSvc.Auth(model);

                if (jwtToken.ResponseInfo.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _authSvc.DeleteAllCookies(_cookiesToDelete);
                    return(Unauthorized(new { LoginError = jwtToken.ResponseInfo.Message }));
                }
                if (jwtToken.ResponseInfo.StatusCode == HttpStatusCode.InternalServerError)
                {
                    _authSvc.DeleteAllCookies(_cookiesToDelete);
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
                if (jwtToken.ResponseInfo.StatusCode == HttpStatusCode.BadRequest)
                {
                    _authSvc.DeleteAllCookies(_cookiesToDelete);
                    return(BadRequest(new { LoginError = jwtToken.ResponseInfo.Message }));
                }

                return(Ok(jwtToken));
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }

            return(Unauthorized());
        }
Beispiel #17
0
        private async Task <IActionResult> RefreshToken(TokenRequestModel model)
        {
            try {
                var rt = _context.Tokens.FirstOrDefault(t => t.ClientId == _appSettings.ClientId && t.Value == model.RefreshToken.ToString());
                if (rt == null)
                {
                    return(new UnauthorizedResult());
                }
                if (rt.ExpiryDate < DateTime.UtcNow)
                {
                    return(new UnauthorizedResult());
                }
                var user = await _userManager.FindByIdAsync(rt.UserId.ToString());

                if (user == null)
                {
                    return(new UnauthorizedResult());
                }
                var rtNew = CreateRefreshToken(rt.ClientId, rt.UserId);
                _context.Tokens.Remove(rt);
                _context.Tokens.Add(rtNew);
                await _context.SaveChangesAsync();

                var response = await CreateAccesToken(user, rtNew.Value);

                var appUser = await _userManager.Users.Include(p => p.Photos).FirstOrDefaultAsync(u => u.UserName == model.Username);

                var userForReturn = _mapper.Map <UserForListDto>(appUser);
                return(Ok(new {
                    authToken = response,
                    user = userForReturn
                }));
            }
            catch (Exception ex) {
                return(new UnauthorizedResult());
            }
        }
Beispiel #18
0
        public IActionResult CreateToken([FromBody] TokenRequestModel requestModelModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var details = Repo.GetUserMaster(requestModelModel.UserEmail);

            if (details == null)
            {
                return(BadRequest("User validation failed"));
            }

            var hashedPassword = _passwordHashingHelper.HashValues(requestModelModel.Password, _passwordHashingHelper.GetSaltFromString(details.Salt));

            if (!string.Equals(hashedPassword, details.UserPassword))
            {
                return(BadRequest("User validation failed"));
            }

            var token = TokenHandler.Create(requestModelModel.UserEmail, AppSettings.Value.SigningKey);

            if (string.IsNullOrEmpty(token))
            {
                return(StatusCode(500));
            }

            var tokenModel = new TokenResponseModel()
            {
                UserEmail   = requestModelModel.UserEmail,
                BearerToken = token
            };

            return(Ok(tokenModel));
        }
Beispiel #19
0
        public async Task GivenTokenRequest_WhenGetToken_ThenGetTokenSuccessful()
        {
            //?Given
            var request      = new TokenRequestModel();
            var tokenReponse = new TokenResponse();
            var expected     = new TokenResponseModel();

            _tokenManager.Setup(x => x.GetToken(It.IsAny <TokenRequest>()))
            .ReturnsAsync(tokenReponse)
            .Verifiable();

            _mapper.Setup(x => x.Map <TokenResponseModel>(tokenReponse))
            .Returns(expected);

            //?When
            var actual = await _authController.GetToken(request);

            //?Then
            Assert.IsAssignableFrom <OkObjectResult>(actual);
            Assert.Equal(((OkObjectResult)actual).Value, expected);

            _tokenManager.Verify();
            _mapper.Verify();
        }
Beispiel #20
0
        public IActionResult Authenticate([FromBody] TokenRequestModel request)
        {
            _logger.LogDebug(string.Format("authenticate api called with parameters. Username:{0} ", request.Username));

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            UserModel objUser = _userService.IsValidUser(request.Username, request.Password);

            if (objUser == null)
            {
                _logger.LogDebug(string.Format("User is not valid. Username:{0} ", request.Username));
                return(BadRequest(ResponseMessageModel.CreateResponseMessage("Invalid User", "Username or password is not correct.")));
            }

            objUser.AccessToken  = objTokenHandler.GenerateJWTToken(objUser.UserID);
            objUser.RefreshToken = objTokenHandler.GenerateRefreshToken();

            _logger.LogDebug(string.Format("Generated access token and refresh token for UserID:{0}", objUser.UserID));

            return(Ok(objUser));
        }
        public async Task <IActionResult> RequestToken([FromBody] TokenRequestModel model)
        {
            var account = await _Context.Accounts.Include(x => x.Organization).FirstOrDefaultAsync(x => x.Mail.ToLower() == model.Account.ToLower() || x.Phone == model.Account);

            if (account == null)
            {
                return(BadRequest(new ErrorRespondModel()
                {
                    Message = "用户名或者密码有误"
                }));
            }

            if (account.Password != model.Password)
            {
                return(BadRequest(new ErrorRespondModel()
                {
                    Message = "用户名或者密码有误"
                }));
            }

            if (account.Frozened)
            {
                return(BadRequest(new ErrorRespondModel()
                {
                    Message = "账户已被冻结"
                }));
            }

            var now = DateTime.UtcNow;

            if (now < account.ActivationTime.AddDays(-1))
            {
                return(BadRequest(new ErrorRespondModel()
                {
                    Message = "账户未启用"
                }));
            }

            if (now > account.Organization.ExpireTime)
            {
                return(BadRequest(new ErrorRespondModel()
                {
                    Message = "账户已失效"
                }));
            }
            else
            {
                //普通用户,过期时间在组织过期时间之内
                if (account.Organization.OwnerId != account.Id)
                {
                    if (now > account.ExpireTime)
                    {
                        return(BadRequest(new ErrorRespondModel()
                        {
                            Message = "账户已失效"
                        }));
                    }
                }
            }


            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_AppConfig.JwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //var claims = new[] { new Claim(ClaimTypes.Name, account.Id) };

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, account.Id)
                , new Claim(ClaimTypes.Role, account.Type)
                , new Claim("OrganizationId", account.OrganizationId)
            };


            var expires = DateTime.Now.AddDays(_AppConfig.JwtSettings.ExpiresDay);
            var token   = new JwtSecurityToken(
                issuer: _AppConfig.JwtSettings.Issuer,
                audience: _AppConfig.JwtSettings.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: creds);

            return(Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token), Expires = expires.ToString("yyyy-MM-dd HH:mm:ss") }));
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Cookies.ContainsKey(AccessToken) || !Request.Cookies.ContainsKey(User_Id))
            {
                Log.Error("No Access Token or User Id found.");
                return(await Task.FromResult(AuthenticateResult.NoResult()));
            }

            if (!AuthenticationHeaderValue.TryParse($"{"Bearer " + Request.Cookies[AccessToken]}",
                                                    out AuthenticationHeaderValue headerValue))
            {
                Log.Error("Could not Parse Token from Authentication Header.");
                return(await Task.FromResult(AuthenticateResult.NoResult()));
            }
            if (!AuthenticationHeaderValue.TryParse($"{"Bearer " + Request.Cookies[User_Id]}",
                                                    out AuthenticationHeaderValue headerValueUid))
            {
                Log.Error("Could not Parse User Id from Authentication Header.");
                return(await Task.FromResult(AuthenticateResult.NoResult()));
            }

            try
            {
                /* STEP 1. Get the Validation Parameters for our applications JWT Token */
                var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                /* STEP 2. Create an instance of Jwt token handler */
                handler = new JwtSecurityTokenHandler();
                /* STEP 3. Create an instance of Jwt token  validation parameters */
                validationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidIssuer      = _appSettings.Site,
                    ValidAudience    = _appSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero
                };

                /* STEP 4. Get the Data protection service instance */
                var protectorProvider = _provider.GetService <IDataProtectionProvider>();
                /* STEP 5. create a protector instance */
                var protector = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
                /* STEP 6. Layer One Unprotect the user id */
                var decryptedUid = protector.Unprotect(headerValueUid.Parameter);
                /* STEP 7. Layer One Unprotect the user token */
                var decryptedToken = protector.Unprotect(headerValue.Parameter);
                /* STEP 8. Create an instance of the user tokenModel */
                TokenModel tokenModel;
                /* STEP 9 Get the existing token for the user from Database */
                /* Step 10. Create a scoped request */
                using (var scope = _provider.CreateScope())
                {
                    var dbContextService = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    var userToken        = dbContextService.Tokens.Include(x => x.User).
                                           FirstOrDefault(ut => ut.UserId == decryptedUid &&
                                                          ut.User.UserName == Request.Cookies[Username] &&
                                                          ut.User.Id == decryptedUid);
                    tokenModel = userToken;
                }

                if (tokenModel == null)
                {
                    return(await Task.FromResult(AuthenticateResult.Fail("You are not authorized to View this Page")));
                }
                /* STEP 11. Apply second layer of decryption using the key store in the token model */
                /* STEP 11.1 Create Protector instance for layer two using token model key */
                /* IMPORTANT - If np key exists or key is invalid - exception will be thrown */
                IDataProtector layerTwoProtector = protectorProvider.CreateProtector(tokenModel?.EncryptionKeyJwt);
                decryptedTokenLayerTwo = layerTwoProtector.Unprotect(decryptedToken);

                /* STEP 12. Validate the token we received - using validation parameters set in step 3 */
                /* IMPORTANT - If the validation fails - the method ValidateToken will throw exception */
                validateToken = handler.ValidateToken(decryptedTokenLayerTwo, validationParameters, out var securityToken);

                /* Checking Token Signature */
                if (!(securityToken is JwtSecurityToken jwtSecurityToken) ||
                    !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
                                                        StringComparison.InvariantCultureIgnoreCase))
                {
                    return(await Task.FromResult(AuthenticateResult.Fail("Your are not authorized")));
                }

                /* STEP 13. Extract the email from the validated token */
                var username = validateToken.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value;

                /* STEP 14. Get User by their email */

                if (Request.Cookies[Username] != username)
                {
                    return(await Task.FromResult(AuthenticateResult.Fail("You are not authorized to View this Page")));
                }

                var user = await _userManager.FindByNameAsync(username);

                /* STEP 15. If user does not exist return authentication failed result */
                if (user == null)
                {
                    return(await Task.FromResult(AuthenticateResult.Fail("You are not authorized to View this Page")));
                }

                /* STEP 16. We need to check if the user belongs to the group of user-roles */

                if (!UserRoles.Contains(user.UserRole))
                {
                    return(await Task.FromResult(AuthenticateResult.Fail("You are not authorized to View this Page")));
                }

                /* STEP 17. Now we will create an authentication ticket, as the token is valid */
                var identity  = new ClaimsIdentity(validateToken.Claims, Scheme.Name);
                var principal = new ClaimsPrincipal(identity);
                var ticket    = new AuthenticationTicket(principal, Scheme.Name);
                return(await Task.FromResult(AuthenticateResult.Success(ticket)));
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(SecurityTokenExpiredException))
                {
                    if (_appSettings.AllowSiteWideTokenRefresh)
                    {
                        var refreshToken = Request.Cookies[RefreshToken];
                        var accessToken  = Request.Cookies[AccessToken];
                        var userId       = Request.Cookies[User_Id];
                        var username     = Request.Cookies[Username];
                        var role         = Request.Cookies[UserRole];


                        if (accessToken != null && userId != null)
                        {
                            // Call the refresh token method if it is valid
                            TokenRequestModel model = new TokenRequestModel
                            {
                                RefreshToken = refreshToken,
                                GrantType    = "refresh_token",
                                UserName     = username
                            };
                            var result = await _authSvc.Auth(model);

                            if (result.ResponseInfo.StatusCode == HttpStatusCode.OK)
                            {
                                var identity  = new ClaimsIdentity(result.Principal.Claims, Scheme.Name);
                                var principal = new ClaimsPrincipal(identity);
                                var ticket    = new AuthenticationTicket(principal, Scheme.Name);
                                return(await Task.FromResult(AuthenticateResult.Success(ticket)));
                            }
                        }
                    }
                }

                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
                return(await Task.FromResult(AuthenticateResult.Fail("Your are not authorized")));
            }
        }
        public IActionResult Token([FromBody] TokenRequestModel requestModel, [FromHeader] string displayLanguage)
        {
            Return <TokenResponseModel> responseModel = new Return <TokenResponseModel>()
            {
                DisplayLanguage = displayLanguage
            };

            // parameter validations
            if (requestModel == null || string.IsNullOrEmpty(requestModel.UserName) || string.IsNullOrEmpty(requestModel.Password))
            {
                responseModel.Status  = ResultStatusCodeStatic.BadRequest;
                responseModel.Message = "Parametreler boş olmamalıdır.";
                responseModel.Success = false;
                ReturnError error = new ReturnError();
                error.Key            = "400";
                error.Message        = "Parametreler boş olmamalıdır.";
                error.Code           = 400;
                responseModel.Errors = new List <ReturnError>();
                responseModel.Errors.Add(error);
                responseModel.Data = null; //hata oluştugundan dolayı Data null olarak dönülür.
                return(BadRequest(responseModel));
            }

            var userLoginResponse = _authenticationService.Login(requestModel.UserName, requestModel.Password, displayLanguage);

            if (userLoginResponse.IsValid)
            {
                responseModel.Data                   = new TokenResponseModel();
                responseModel.Data.Id                = userLoginResponse.Personnel.Id;
                responseModel.Data.TC                = userLoginResponse.Personnel.TC;
                responseModel.Data.Name              = userLoginResponse.Personnel.Name;
                responseModel.Data.LastName          = userLoginResponse.Personnel.LastName;
                responseModel.Data.Phone             = userLoginResponse.Personnel.Phone;
                responseModel.Data.Address           = userLoginResponse.Personnel.Address;
                responseModel.Data.UserName          = userLoginResponse.Personnel.UserName;
                responseModel.Data.Password          = "******";
                responseModel.Data.TokenExpirePeriod = 60;

                // kullanıcının authcode bilgileri elde edilir
                var userAuthCodeListAsString = _profileDetailService.GetAllAuthCodeByPersonnelIdAsConcatenateString(userLoginResponse.Personnel.Id);

                //jwt token eklenmesi işlevi
                responseModel.Data.UserToken = TokenHelper.CreateToken(userLoginResponse.Personnel, userAuthCodeListAsString); //userToken.Token;

                responseModel.Status  = ResultStatusCodeStatic.Success;
                responseModel.Message = "Success";
                responseModel.Success = true;
                return(Ok(responseModel));
            }
            else
            {
                responseModel.Status  = ResultStatusCodeStatic.InternalServerError;
                responseModel.Message = userLoginResponse.ErrorMessage;
                responseModel.Success = false;
                ReturnError error = new ReturnError();
                error.Key            = "500";
                error.Message        = userLoginResponse.ErrorMessage;
                error.Code           = 500;
                responseModel.Errors = new List <ReturnError>();
                responseModel.Errors.Add(error);
                responseModel.Data = null; //hata oluştugundan dolayı Data null olarak dönülür.
                                           // return BadRequest(responseModel);
                                           //return Ok(responseModel);
                return(BadRequest(responseModel));
            }
        }
Beispiel #24
0
        public IActionResult GetToken([FromBody] TokenRequestModel model)
        {
            var tokenEncoded = HashFactory.GenerateToken(model);

            return(new OkObjectResult(new { token = tokenEncoded }));
        }
        //public Task<NotificationOutcome> TokenRequest(string pns, TokenRequestModel model)
        //{
        //    throw new NotImplementedException();
        //}


        private string TokenRequestModelAPNS(TokenRequestModel model)
        {
            string ret = JsonConvert.SerializeObject(model);

            return(ret);
        }
Beispiel #26
0
        public async Task <AuthenticationModel> LoginAsync(TokenRequestModel model)
        {
            var result = await _userService.LoginAsync(model);

            return(result);
        }
        /// <summary>
        /// Note: Although the Apple devicetoken is stored in pass-in, but at the time the devicetoken was registered through our Account/RegisterPhoneToken,
        /// Azure Notification Hub is associated userId to the DeviceToken.  So the UserId is the real identifier (not the APNS devicetoken), userId_[12125...] is the real key.
        /// </summary>
        /// <param name="pns"></param>
        /// <param name="userId"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <NotificationOutcome> TokenRequest(NotificationHubPNS pns, string userId, TokenRequestModel model)
        {
            string[] userTag = new string[1];
            userTag[0] = "userId_" + userId.Trim();

            Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
            switch (pns)
            {
            case NotificationHubPNS.APNS:
                // iOS

                string serializeModel = TokenRequestModelAPNS(model);

                string logStr = string.Format("APNS TokenRequest SerializeModel: {0}", serializeModel);
                logger.Debug(logStr);

                int n = serializeModel.IndexOf('{');
                if (n >= 0)
                {
                    serializeModel = serializeModel.Remove(n, 1);
                }

                n = serializeModel.LastIndexOf('}');
                if (n > 0)
                {
                    serializeModel = serializeModel.Remove(n, 1);
                }

                string alert = "{";
                alert += "\"aps\":{\"alert\":\"" + "vid: " + model.vid + ", tid " + model.tid + ", merchant " + model.merchantIdentifier + "\", \"sound\":\"default\"},";
                alert += serializeModel;
                alert += "}";

                logStr = string.Format("APNS TokenRequest Alert: {0}", alert);
                logger.Debug(logStr);

                //outcome = await Hub.SendAppleNativeNotificationAsync(alert);

                if (!string.IsNullOrEmpty(userId))
                {
                    outcome = await Hub.SendAppleNativeNotificationAsync(alert, userTag);
                }
                else
                {
                    outcome = await Hub.SendAppleNativeNotificationAsync(alert);
                }
                break;
            }
            return(outcome);
        }
Beispiel #28
0
        public async Task <IActionResult> GetTokenAsync(TokenRequestModel model)
        {
            var result = await _userService.GetTokenAsync(model);

            return(Ok(result));
        }
        public IHttpActionResult PayRequest(PayRequestBindingModel model)
        {
            string slog = string.Format("PayRequest Begin model: {0}", JsonConvert.SerializeObject(model));

            logger.Debug(slog);

            PayResponseBindingModel pr = new PayResponseBindingModel()
            {
                msgId  = 2,
                tid    = model.tid,
                token  = "",
                status = 2
            };

            if (!ModelState.IsValid)
            {
                logger.Debug("PayRequest ModelState is invalid");
                pr.status = -1;
                return(Ok(pr));
            }


            ///////////////////////////////////////
            // Check for valid vid or email
            ///////////////////////////////////////
            User user = userService.GetUserByEmail(model.vid);

            if (user == null)
            {
                // Invalid user email
                pr.status = 1;
                return(Ok(pr));
            }
            else if (user != null && user.EmailConfirmed == false)
            {
                // User hasn't confirmed email.
                pr.status = 1;
                return(Ok(pr));
            }

            ///////////////////////////////////////
            // Check for valid merchant
            ///////////////////////////////////////
            Merchant merchant = merchantService.GetMerchantByAlias(model.merchantIdentifier);

            if (merchant == null)
            {
                // Invalid merchant
                pr.status = 2;
                return(Ok(pr));
            }

            var pay = new PaymentLog()
            {
                TId                           = model.tid.ToString(),
                TTime                         = model.ttime,
                ShippingInfo                  = model.shippingInfo,
                Amount                        = model.amount,
                CountryCode                   = model.countryCode,
                CurrencyCode                  = model.currencyCode,
                MerchantId                    = model.merchantIdentifier,
                MechantName                   = model.merchantName,
                LineItems                     = model.lineItems,
                PublicKey                     = model.publicKey,
                Email                         = model.vid,
                MerchantCapability            = merchant.MerchantCapabilities,
                SupportedNetwork              = merchant.SupportNetwork,
                PaymentMethodTokenizationType = merchant.PaymnetMethodTokenizationType,
                CodeCheck                     = string.Empty,
                CodeCheckCount                = 0,
                IsCodeCheckValidated          = false
            };

            string codeCheck           = GetRamdomCodeCheck();
            bool   correctShippingInfo = paymentService.IsValidUserShippingInfo(user, model.shippingInfo);

            if (!correctShippingInfo)
            {
                pay.CodeCheck = codeCheck;
            }

            ///////////////////////////////////////
            // Save payment to database PaymentLog table
            ///////////////////////////////////////
            PaymentLog checkLog = paymentService.GetPaymentByTid(pay.TId);

            if (checkLog == null)
            {
                // Save pay to the database
                string val = paymentService.RequestPay(pay);
                if (string.IsNullOrEmpty(val))
                {
                    //ModelState.AddModelError("", string.Format("Error PayRequest"));
                    //return BadRequest(ModelState);
                    logger.Debug("PayRequest can't add to the database PaymentLog table");
                    pr.status = -1;
                    return(Ok(pr));
                }
            }
            //else
            //{
            //    //ModelState.AddModelError("", string.Format("Error tid is already exist"));

            //    return BadRequest(ModelState);
            //}

            ///////////////////////////////////////
            // Check to make sure Shipping Info is to the vid or email user
            ///////////////////////////////////////
            if (!correctShippingInfo)
            {
                ///////////////////////////////////////
                // Insert key to PayTokenManager PaymentRequest
                ///////////////////////////////////////
                PayTokenManager.Instance.SavePaymentLog(model.tid, pay);

                // Send CodeCheck back to the browser
                CodeCommandBindingModel codeCommand = new CodeCommandBindingModel()
                {
                    msgId = 5,
                    tid   = model.tid,
                    code  = codeCheck
                };
                return(Ok(codeCommand));
            }

            try
            {
                ///////////////////////////////////////
                // Get token value from PayTokenManger
                ///////////////////////////////////////

                TokenRequestModel trModel = PaymentLogToTokenRequestModel(pay, user, merchant);
                string            token   = SendMobileTokenRequest(model.tid, user.Id, trModel);
                if (!string.IsNullOrEmpty(token))
                {
                    pr.status = 0;
                }
                else
                {
                    pr.status = 4;
                }
                pr.token = token;


                /*
                 * ///////////////////////////////////////
                 * // Notify the mobile applet
                 * ///////////////////////////////////////
                 * TokenRequestModel trModel = PaymentLogToTokenRequestModel(model, user, merchant);
                 * notificationService.TokenRequest(Global.NotificationHubPNS.APNS, user.Id, trModel);
                 *
                 * ///////////////////////////////////////
                 * // Insert key to PayTokenManager
                 * ///////////////////////////////////////
                 * PayTokenManager.Instance.Save(model.tid, string.Empty);
                 *
                 * ///////////////////////////////////////
                 * // Waiting for TokenResponse from applet to update the PayTokenManager
                 * ///////////////////////////////////////
                 *
                 * int timerPayRequest = 10;
                 * int.TryParse(ConfigurationManager.AppSettings["TimerPayRequest"].ToString(), out timerPayRequest);
                 *
                 * timerPayRequest *= 1000;
                 *
                 * int tCount = 30;
                 * int interval = timerPayRequest / tCount;
                 * int timer = 0;
                 * while (timer < timerPayRequest)
                 * {
                 *  Thread.Sleep(interval);
                 *  timer += interval;
                 *  string tok;
                 *  PayTokenManager.Instance.Get(model.tid, out tok);
                 *  if (!string.IsNullOrEmpty(tok))
                 *  {
                 *      break;
                 *  }
                 * }
                 *
                 * ///////////////////////////////////////
                 * // Get token value from PayTokenManger
                 * ///////////////////////////////////////
                 * string token = "";
                 * if (PayTokenManager.Instance.Get(model.tid, out token) && !string.IsNullOrEmpty(token))
                 * {
                 *  pr.status = 0;
                 *  PayTokenManager.Instance.Delete(model.tid);
                 * }
                 * else
                 * {
                 *  pr.status = 4;
                 * }
                 * pr.token = token;
                 */

                if (pr.status == 0)
                {
                    paymentService.SavePaymentRequestConfimred(model.tid.ToString());
                }
                else
                {
                    paymentService.SavePaymentRequestRejected(model.tid.ToString());
                }
                PayTokenManager.Instance.Delete(model.tid);
            }
            catch (MessagingException e)
            {
                logger.Error("PayRequest MessageException", e);
                //ReturnGoneIfHubResponseIsGone(e);
                pr.status = 4;
                return(Ok(pr));
            }
            catch (Exception ex)
            {
                logger.Error("PayRequest", ex);
                pr.status = 4;
                return(Ok(pr));
            }

            slog = string.Format("PayRequest Returns: {0}", JsonConvert.SerializeObject(pr));
            logger.Debug(slog);

            return(Ok(pr));
        }
        public async Task<IActionResult> RefreshingTokens([FromBody] TokenRequestModel model)
        {
            TokenResponseModel responseModel = await _jwtProvider.RefreshTokensAsync(model.AccessToken, model.RefreshToken);

            return Ok(responseModel);
        }