public void Should_Skip_Processig() { var requestDelegate = Substitute.For <RequestDelegate>(); var middleware = new TokenProviderMiddleware(requestDelegate, Options.Create(new TokenProviderOptions())); var context = new DefaultHttpContext(); middleware.Invoke(context, null); var calls = requestDelegate.ReceivedWithAnyArgs(1); }
public async void Should_Return_Bad_Request_Response() { TokenProviderMiddleware middleware = GetMiddleware(); var context = new DefaultHttpContext(); context.Request.Method = "GET"; context.Request.Path = TokenProviderOptionFactory.PATH; await middleware.Invoke(context, null); Assert.Equal(400, context.Response.StatusCode); }
public async Task <SignInResponseModel> FacebookLogin([FromBody] FacebookLoginModel model) { if (model == null || !ModelState.IsValid) { throw new CustomException(Errors.INVALID_REQUEST, Errors.INVALID_REQUEST_MSG); } var verifyResult = await this.VerifyFacebookAccessToken(model.AccessToken); if (verifyResult.IsValid) { var existAccount = await _accountService.FindByExternalProviderAsync("facebook", verifyResult.FacebookId); if (existAccount == null) { throw new CustomException(Errors.ACCOUNT_NOT_FOUND, Errors.ACCOUNT_NOT_FOUND_MSG); } else if (existAccount.Status == UserStatus.InActive) { throw new CustomException(Errors.ACCOUNT_INACTIVE, Errors.ACCOUNT_INACTIVE_MSG); } if (existAccount.AccountType == JobHop.Common.Enums.AccountType.Jobseeker && !existAccount.PhoneNumberVerified) { //return phone number in message for verify throw new CustomException(Errors.WAIT_FOR_VERIFICATION, existAccount.PhoneNumber); } var uname = string.IsNullOrEmpty(existAccount.UserName) ? $"Facebook:{verifyResult.FacebookId}" : existAccount.UserName; var permissions = await _accountService.GetPermissionsOfAccountAsync(existAccount.Id); var now = DateTime.UtcNow; var encodedJwt = TokenProviderMiddleware.GenerateAccessToken(_tokenOptions, now, uname, existAccount.Id.ToString(), permissions.ToArray()); var response = new SignInResponseModel { AccessToken = encodedJwt, Expires = now.AddSeconds((int)_tokenOptions.Expiration.TotalSeconds), Account = existAccount.ToViewModel() }; return(response); } else { throw new CustomException(Errors.INVALID_REQUEST, Errors.INVALID_REQUEST_MSG); } }
public async Task <IActionResult> Token(string username, string password) { var json = ""; var agent = await _agentsService.GetAgentByUserPass(username, password); if (agent == null) { return(null); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, agent["username"].ToString()), new Claim(ClaimTypes.Role, agent["role"].ToString()), new Claim("user_id", agent["id"].ToString()), new Claim("name", agent["name"].ToString()), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, TokenProviderMiddleware.ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64) }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { user_id = agent["id"].ToString(), access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds, role = (string)agent["role"], business_id = (string)agent["business_id"], }; json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
public TokenProviderMiddlewareTests() { _jwtTokenDecrypt = new JWTTokenDecrypt(); //_loggerFactory = new Mock<ILoggerFactory>(); _participantApplication = new Mock <IParticipantApplication>(); string secretKey = "d71a5f83-8132-4c50-acd0-96ed6ebbf61d"; var signingKey = new SymmetricSecurityKey(ASCIIEncoding.ASCII.GetBytes(secretKey)); var tokenProviderOptions = new TokenProviderOptions { Path = "/token", Audience = "Audience", Issuer = "Issuer", SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) }; var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = "Issuer", ValidateAudience = true, ValidAudience = "Audience", ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; Configuration.TokenKey = "Q2FpeGFNYWlzVmFudGFnZW5zTFRN"; Configuration.Expiration = 15; _participantApplication.Setup(x => x.GetByCpf("12345678900")).Returns(ParticipantStub.Participante()); _tokenProviderMiddleware = new TokenProviderMiddleware(null, Options.Create(tokenProviderOptions), tokenValidationParameters, _loggerFactory.Object, _participantApplication.Object); }
public AccountController(IUnitOfWork uow, UserManager <User> userManager, SignInManager <User> signInManager, IOptions <JwtIssuerOptions> jwtOptions, ILoggerFactory loggerFactory, TokenProviderMiddleware tokenProviderMiddleware ) : base(uow) { this._userManager = userManager; this._jwtOptions = jwtOptions.Value; this._tokenProviderMiddleware = tokenProviderMiddleware; tokenProviderMiddleware.ThrowIfInvalidOptions(this._jwtOptions); _logger = loggerFactory.CreateLogger <AccountController>(); _serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; }