public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "generate-access-token")] HttpRequest req, ILogger log) { // To get the private key, call the GenerateKeyPairContoller API var privateKey = "MIIEpQIBAAKCAQEA7oGXGFiW63LXxxi2So4Y19wbp8R7ij1iFn7EvFJnDHcvKvi+VLSdmvJjDf/eJDDRestuSN5MS6+35kvl74nSqXPDmTFjCWWQQlqPBX0S7K2XOtg7l/goBGwPMF47AM7gEbqR2WXDoVwy/ALwPeRZhCQrKM9aIx+FjRpZSnU4sYF7zUDpKeb6VjcpyPc9qxPGsIRqKBECHQIpzgq90/UAsqQRK3+QktXPhxOiDna372D5P5MIXx1lziXiZ2bdxJezPkgfUgLC0xO3BUuaxt+KPg9vRcYjVd/Rpo1K+zi9zMKvTCMMFZWBFNqvZXvmZ0oQvJiGhXcFdXCIWwjHPjlJkQIDAQABAoIBAQCB3fRM4GgE+jp+AXm47NigKQyx9C2knznar9omBORxiDAZwOm6K8KpjRPcmpb1s9NMfpqleM2oZJzI/EjOfohDlnJJ5vdbNX8wcijwPyNf1kHDW9xPKmN3zPMUTirojLy7SpCCBIRaR17HlD4GJWGMrzkE9qrI9y/8Hf3CqkNdeuu7BmZ+mQ5uAcZw9M7bdCorADWuX1k+GA/mW1d1/F0vPbx4cN8qShFh6fjzDvteFVABMN0NzOZR240Qjfbdb7Ho+TAGAAsEd6niHTEXlIX/t4UQAmLMImF0a8uYWDJX+5aq5uQBH2S8yvXDBJVAuZXTIC/j1K3Qf2kj0XVYRz01AoGBAPdTeRGASCN6EIAlAIGrLYjr9icNlu7l3fX+0koyDGsSLXTLLGglzWKEt/NaqnVmPgf05s4PIpLFXHo1vY9fNAQ0go6idJ7LcQLjcysxrw6YK5ZNZW5MmkdiemowmXm0acTAZEkyqqPbvCgEvgcrv8i9Y2YVfNZp63bkMOictlY/AoGBAPbe7nLTlW8jt1l3k8PLtY/g/YKCWr4Hj+HlIo7tPiOUSjE2J4AgHrtVc18fSrX8CSMwigy14MDsCOV8LvW3gTsAxI+UYyPu0smkH2Qp4MbqJyliujPnELbukth/WvG1feDoZ/yV+YV6YAPlJ5zzbBqcHVaHQnaTE2wTbjJ7K4wvAoGAOkG6Ocoas+iTrGuK1ABLKH5UK9zCmaEhiEkupXVmgW31sRYObrXAzBzw62yGzEJ6CAvCtfTQsvu0DcFM1lGZgggQXKKdj63h/8ktnpYEYw6q7atrYfC/QmNK7GpoLEe3xjV/KdK6aQBgMJj1XeELOrCJkkkrb6Hhac7USmZneKcCgYEAuETSy1bvVdPdCaTd4OnvDgQsdfwC65ENbtnvn6uqFDid4HnBpjtTdRVlVn0u8QO9dkzG3pHrv1TvlwvIqZRdm8MI9PsXvTyIjgY5gDRaGV+x94w/3Hn+2ezeI0d8hKqp2PTgmYMAiwc7H+0uUlLIQFyC8ZFopMVHXAZs3LVfXfUCgYEAm8DuYo7lUjA9/kmntGCbEgLeMZNJsPqVn6HPfFlgFXD1ByUWoBGVZEgWDZxp0KoNXT6gIWYQPx3aUmDflJu8b2fQsoW/U11GUSQu05VE+O2E133UhGnalQBRlWGSxKOrjCf409cwXCEZaNJyrZ7yNn6tk/lTCMrokVbuJOIDswE="; var notBefore = DateTime.UtcNow; // optional claims var additionalClaims = new List <Claim> { new Claim(JwtRegisteredClaimNames.GivenName, "Albert"), new Claim(JwtRegisteredClaimNames.FamilyName, "Brucelee") }; var accessToken = AccessTokenGenerator.GenerateAccessToken( userId: "test123", privateKey: privateKey, issuer: "TomcatSadis.AuthService", audience: "TomcatSadis.AccessTokenHandler", notBefore: notBefore, expires: notBefore.AddSeconds(31104000), additionClaims: additionalClaims); return(new OkObjectResult(accessToken)); }
public UserAccount TokenValidate(string authHeader) { var accessToken = AccessTokenGenerator.DecryptToken(authHeader); var cacheKeyPrefix = "FiiiShop:Token:"; var cacheKey = $"{cacheKeyPrefix}{accessToken.Identity}"; var cacheToken = RedisHelper.StringGet(Constant.REDIS_TOKEN_DBINDEX, cacheKey); if (string.IsNullOrEmpty(cacheToken)) { throw new AccessTokenExpireException(); } if (authHeader != cacheToken) { throw new UnauthorizedException(); } var id = Guid.Parse(accessToken.Identity); var account = new UserAccountDAC().GetById(id); if (account == null) { throw new UnauthorizedException(); } if (account.Status == 0) { //已经禁用的用户,删除token RedisHelper.KeyDelete(Constant.REDIS_TOKEN_DBINDEX, cacheKey); throw new CommonException(ReasonCode.ACCOUNT_DISABLED, "Invalid user"); } RedisHelper.StringSet(Constant.REDIS_TOKEN_DBINDEX, cacheKey, cacheToken, TimeSpan.FromSeconds(AccessTokenGenerator.DefaultExpiryTime)); return(account); }
public static Token GenerateToken(User user, IAccessTokenSettings accessTokenSettings) { var claims = new List <System.Security.Claims.Claim> { new System.Security.Claims.Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new System.Security.Claims.Claim(JwtRegisteredClaimNames.FamilyName, user.LastName) }; if (user.Claims != null && user.Claims.Count > 0) { user.Claims.ForEach((claim) => { claims.Add(new System.Security.Claims.Claim(claim.Type, claim.Value)); }); } var accessToken = AccessTokenGenerator.GenerateAccessToken( userId: user.Id.ToString(), privateKey: accessTokenSettings.PrivateKey, issuer: accessTokenSettings.Issuer, audience: accessTokenSettings.Audience, notBefore: accessTokenSettings.NotBefore, expires: accessTokenSettings.Expires, additionClaims: claims); return(new Token( accessToken: accessToken, expiresIn: accessTokenSettings.ExpiresIn)); }
public Authenticator(AccessTokenGenerator accessTokenGenerator, RefreshTokenGenerator refreshTokenGenerator, IRefreshTokenRepository refreshTokenRepository) { _accessTokenGenerator = accessTokenGenerator; _refreshTokenGenerator = refreshTokenGenerator; _refreshTokenRepository = refreshTokenRepository; }
public void GeneratedAccessTokenShouldBeValid( string privateKey, string issuer, string audience, string notBefore, double expiresIn, string userId, string givenName, string familyName, string expectedAccessToken) { var notBeforeDateTime = DateTime.Parse(notBefore); var additionalClaims = new List <Claim> { new Claim(JwtRegisteredClaimNames.GivenName, givenName), new Claim(JwtRegisteredClaimNames.FamilyName, familyName) }; var accessToken = AccessTokenGenerator.GenerateAccessToken( userId: userId, privateKey: privateKey, issuer: issuer, audience: audience, notBefore: notBeforeDateTime, expires: notBeforeDateTime.AddSeconds(expiresIn), additionClaims: additionalClaims); Assert.Equal(expectedAccessToken, accessToken); }
public UserController(UserManager <User> userManager, RoleManager <IdentityRole> roleManager, IConfiguration configuration, AccessTokenGenerator accessTokenGenerator) { _userManager = userManager; _roleManager = roleManager; _configuration = configuration; _accessTokenGenerator = accessTokenGenerator; }
public void GenerateRandomString_validLength_returnsRandomString() { const int size = 8; var randomString = AccessTokenGenerator.Generate(size); Assert.IsNotNull(randomString); Assert.AreEqual(size, randomString.Length); }
/// <summary>Asynchronously authenticates the request.</summary> /// <returns>The task that completes the authentication.</returns> /// <param name="context">The authentication context.</param> /// <param name="cancellationToken">The cancellation token.</param> public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException(nameof(context)); } HttpRequestMessage request = context.Request; if (request == null) { throw new InvalidOperationException("Request must not be null"); } if (context.ActionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Count > 0) { return; } if (context.Request.Headers.Authorization == null) { Unauthorized(context); return; } try { var authHeader = request.Headers.Authorization.Parameter; var accessToken = JsonConvert.DeserializeObject <AccessToken>(AccessTokenGenerator.DecryptToken(authHeader)); string cacheToken = RedisHelper.StringGet($"{SystemPlatform.FiiiCoinWork}:Investor:{accessToken.Username}"); if (authHeader == cacheToken) { var bc = new InvestorAccountComponent(); InvestorAccount account = bc.GetByUsername(accessToken.Username); if (account.Status == AccountStatus.Locked) { AccountLocked(context); return; } string lan = context.Request.Headers.AcceptLanguage.FirstOrDefault()?.Value ?? "en"; RedisHelper.StringSet($"{SystemPlatform.FiiiCoinWork}:Language:{account.Username}", lan); SetSecurityPrincipal(ref context, account); } else { Unauthorized(context); } } catch (Exception) { Unauthorized(context); } }
private static ITellerApiClient GetTellerApiClient(string apiBaseUrl, string clientId, string clientSecret, string identityProvider) { var apiClientOptions = new ApiClientOptions { ApiBaseUrl = apiBaseUrl, TokenHeader = AccessTokenGenerator.GetReferenceTokenHeader(identityProvider, clientId, clientSecret) }; return(new TellerApiClient(apiClientOptions, BackfillManager.Logger)); }
public void Generate_Token() { const int expectedExpiresIn = 300000; var sut = new AccessTokenGenerator(); var actualResult = sut.CreateAccessToken("aGVsbG9mcmVzaGdvX2JlX3Rlc3Q=", "sub", "iss", "aud"); actualResult.Token.Should().NotBeNull(); actualResult.ExpiresIn.Should().Be(expectedExpiresIn); }
/// <summary> /// constructor AuthController through the passed parameters enables the implementation of authorization /// </summary> /// <param name="context"></param> /// <param name="userRepository"></param> /// <param name="passwordHasher"></param> /// <param name="accessTokenGenerator"></param> public AuthController(DatabaseContext context, IBaseUserModelRepository userRepository, IPasswordHasher passwordHasher, AccessTokenGenerator accessTokenGenerator) { Context = context; UserRepository = userRepository; PasswordHasher = passwordHasher; AccessTokenGenerator = accessTokenGenerator; }
/// <summary> /// Generates access token if password matches. If not - returns null /// </summary> /// <param name="password">password</param> /// <returns>new access token</returns> public string GenerateAccessToken(string password) { if (!_passwordComparator.ArePasswordsSame(_hashedPassword, password)) { return(null); } var accessToken = AccessTokenGenerator.Generate(AccessTokenLength); _accessTokens.Add(accessToken); return(accessToken); }
public UserAccount Token(string authHeader, string lang) { var accessToken = AccessTokenGenerator.DecryptToken(authHeader); var cacheKeyPrefix = "FiiiPay:Token:"; var cacheKey = $"{cacheKeyPrefix}{accessToken.Identity}"; var cacheToken = RedisHelper.StringGet(Constant.REDIS_TOKEN_DBINDEX, cacheKey); //var cacheManager = new FiiiPayRedisCacheManager(); //var cacheToken = cacheManager.GetToken(accessToken.Identity); if (string.IsNullOrEmpty(cacheToken)) { throw new AccessTokenExpireException(); } if (authHeader != cacheToken) { throw new UnauthorizedException(); } var id = Guid.Parse(accessToken.Identity); var account = new UserAccountComponent().GetById(id); //var account = cacheManager.GetUserAccount(accessToken.Identity); if (account == null) { throw new UnauthorizedException(); } if (account.Status == 0) { //已经禁用的用户,删除token RedisHelper.KeyDelete(Constant.REDIS_TOKEN_DBINDEX, cacheKey); //cacheManager.DeleteToken(accessToken.Identity); throw new CommonException(ReasonCode.ACCOUNT_DISABLED, MessageResources.AccountDisabled); } RedisHelper.StringSet(Constant.REDIS_TOKEN_DBINDEX, cacheKey, cacheToken, TimeSpan.FromSeconds(AccessTokenGenerator.DefaultExpiryTime)); if (!string.IsNullOrEmpty(lang)) { new UserAccountComponent().ChangeLanguage(account.Id, lang); } //account.Id = Guid.Parse(accessToken.Identity); //account.Language = lang; //cacheManager.ExpireToken(accessToken.Identity); //cacheManager.ChangeLanguage(accessToken.Identity, lang); return(account); }
private SignonDTO IssueAccessToken(InvestorAccount user) { var accessToken = AccessTokenGenerator.IssueToken(user.Username); var keyLoginToken = $"{SystemPlatform.FiiiCoinWork}:Investor:{user.Username}"; RedisHelper.StringSet(keyLoginToken, accessToken, TimeSpan.FromSeconds(AccessTokenGenerator.EXPIRY_TIME)); return(new SignonDTO { AccessToken = accessToken }); }
public void GenerateRandomStrings_validLength_returnsDifferentStrings() { const int size = 8; var accessTokens = new List <string>(); for (var i = 0; i < 100; i++) { var newToken = AccessTokenGenerator.Generate(size); if (accessTokens.Contains(newToken)) { Assert.Fail($"token {newToken} already exists on the list! ({i} iteration)"); } accessTokens.Add(newToken); } }
public bool Auth(Guid clientId, string username, string password) { var accessModel = AccessTokenGenerator.DecryptToken(password); switch (accessModel.Platform) { case SystemPlatform.FiiiPay: return(Guid.TryParse(accessModel.Identity, out var userId) && clientId == userId); case SystemPlatform.FiiiPOS: return(accessModel.Identity == username); default: return(false); } }
/// <summary> /// 生成Web token /// </summary> /// <param name="userId"></param> /// <param name="accessToken"></param> /// <returns></returns> public static bool SetWebTokenIndRedis(string merchantId, out string accessToken) { accessToken = null; if (string.IsNullOrEmpty(merchantId)) { return(false); } string key = WebConfig.Redis_Key_Token + merchantId.ToString(); accessToken = AccessTokenGenerator.IssueToken(merchantId); bool result = RedisHelper.StringSet(WebConfig.RedisDB_Web, key, accessToken, new TimeSpan(0, 0, WebConfig.RedisDB_Token_ExpireTime)); return(result); }
private LoginOM IssueAccessToken(UserAccount user) { var keyLoginTokenPrefix = "FiiiPay:Token:"; var keyLoginToken = $"{keyLoginTokenPrefix}{user.Id}"; var accessToken = AccessTokenGenerator.IssueToken(user.Id.ToString()); //new FiiiPayRedisCacheManager().SetToken(user.Id, accessToken); RedisHelper.StringSet(Constant.REDIS_TOKEN_DBINDEX, keyLoginToken, accessToken, TimeSpan.FromSeconds(AccessTokenGenerator.DefaultExpiryTime)); var expiresTime = DateTime.UtcNow.AddSeconds(AccessTokenGenerator.DefaultExpiryTime); return(new LoginOM { AccessToken = accessToken, ExpiresTime = expiresTime.ToUnixTime().ToString(), UserInfo = GetSimpleUserInfoOM(user) }); }
public Common.Message.AuthorizationResult CheckAccess(Common.Message.AuthorizationRequest request) { AuthorizationResult result = new AuthorizationResult(); TokenValidator tokenValidator = new TokenValidator(); var validationResult = tokenValidator.ValiateIdentityToken(request.IdentityToken); if (validationResult.IsError) { result.ErrorMessage = validationResult.Error; return(result); } AccessTokenGenerator generator = new AccessTokenGenerator(); var accessToken = generator.GenerateToken(request.IdentityToken, request.Resource); result.AccessToken = accessToken; return(result); }
private SignonDTO GetAccessToken(POS pos, MerchantAccount account) { MerchantAccessToken token = new MerchantAccessToken { POSSN = pos.Sn, Identity = account.Username }; string accessToken = AccessTokenGenerator.IssueToken(token); string key = $"{RedisKeys.FiiiPOS_APP_MerchantId}:{account.Username}"; RedisHelper.StringSet(Constant.REDIS_TOKEN_DBINDEX, key, accessToken); return(new SignonDTO { AccessToken = accessToken, SecretKey = account.SecretKey }); }
public void Execute(IServiceCollection services, IServiceProvider serviceProvider) { AccessTokenGenerator accessTokenGenerator = serviceProvider.GetService <AccessTokenGenerator>(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; } ).AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, IssuerSigningKey = accessTokenGenerator.CreateSecurityKey() }; } ); }
/// <summary> /// 获取web token 里的userName /// </summary> /// <param name="token"></param> /// <param name="userName"></param> /// <returns></returns> public static bool GetWebTokenIndRedis(string token, out string userName) { userName = string.Empty; AccessToken accessToken = AccessTokenGenerator.DecryptToken(token); if (accessToken == null) { return(false); } string key = WebConfig.Redis_Key_Token + accessToken.Identity; string redisToken = RedisHelper.StringGet(WebConfig.RedisDB_Web, key); if (redisToken != token) { return(false); } userName = accessToken.Identity; return(true); }
public AuthenticationController(IUserRepository userRepository, IPasswordHasher passwordHasher, AccessTokenGenerator accessTokenGenerator, RefreshTokenGenerator refreshTokenGenerator, RefreshTokenValidator refreshTokenValidator, IRefreshTokenRepository refreshTokenRepository, Authenticator authenticator) { _userRepository = userRepository; _passwordHasher = passwordHasher; _refreshTokenValidator = refreshTokenValidator; _refreshTokenRepository = refreshTokenRepository; _authenticator = authenticator; }
/// <summary>Asynchronously authenticates the request.</summary> /// <returns>The task that completes the authentication.</returns> /// <param name="context">The authentication context.</param> /// <param name="cancellationToken">The cancellation token.</param> public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException(nameof(context)); } HttpRequestMessage request = context.Request; if (request == null) { throw new InvalidOperationException("Request must not be null"); } if (context.ActionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Count > 0) { return(Task.FromResult(0)); } if (context.Request.Headers.Authorization == null) { return(Unauthorized(context)); } try { var authHeader = request.Headers.Authorization.Parameter; var accessToken = AccessTokenGenerator.DecryptToken <MerchantAccessToken>(authHeader); if (string.IsNullOrWhiteSpace(accessToken.Identity)) { var merchant = new MerchantAccountComponent().GetMerchantAccountBySN(accessToken.POSSN); if (merchant == null) { return(Unauthorized(context)); } accessToken.Identity = merchant.Username; } var cacheKey = $"{RedisKeys.FiiiPOS_APP_MerchantId}:{accessToken.Identity}"; var cacheToken = RedisHelper.StringGet(Constant.REDIS_TOKEN_DBINDEX, cacheKey); if (authHeader != cacheToken) { return(Unauthorized(context)); } var bc = new MerchantAccountComponent(); var account = bc.GetByPosSn(accessToken.POSSN, accessToken.Identity); if (account == null) { return(Unauthorized(context)); } bc.ChangeLanguage(account.Id, context.Request.Headers.AcceptLanguage.FirstOrDefault()?.Value); var webContext = new WebContext { Id = account.Id, CountrtId = account.CountryId, Name = account.MerchantName }; context.Principal = new WebPrincipal(new WebIdentity(webContext)); return(Task.FromResult(0)); } catch (CommonException ex) { return(CommonErrorResult(context, ex)); } catch (Exception) { return(Unauthorized(context)); } }
public AuthTests() { _configuration = CreateMockConfiguration(); _accessTokenGenerator = new AccessTokenGenerator(); }