/// <summary> /// Generate auth token for the user /// use Password to encrypt the new generated token /// </summary> /// <param name="authTokenRequest">phone , password</param> /// <returns> return AuthTokenResponse(validation errors + token string)</returns> public AuthTokenResponse GenerateAuthToken(AuthTokenRequest authTokenRequest) { var result = new AuthTokenResponse(); var error = ValidateRequest(authTokenRequest); if (error.HasErrors) { result.Errors = error; return(result); } var createdAt = DateTime.UtcNow; var authTokenRow = new DTO.AuthToken(); authTokenRow.Password = authTokenRequest.Password; authTokenRow.Phone = authTokenRequest.Phone; authTokenRow.ExpireAt = createdAt.AddHours(1); authTokenRow.Token = GenerateToken(authTokenRequest.Password, createdAt); _authTokenRepository.Add(authTokenRow); result.Token = authTokenRow.Token; return(result); }
private Task <string> GetTokenAsync() { var tokenRequest = new AuthTokenRequest(region, subscriptionKey); return(tokenRequest .DecodeAsync(new StringFactory())); }
public (bool authenticatedSuccessfully, string token) IssueToken(AuthTokenRequest tokenRequest) { if (tokenRequest == null) { throw new ArgumentNullException(nameof(tokenRequest)); } // Here you can implement username/password verification instead if (tokenRequest.ClientId != DEFAULT_CLIENT_ID) { return(false, null); } var jwtToken = new JwtSecurityToken( _tokenOpts.Issuer, _tokenOpts.Audience, new [] { new Claim(JwtRegisteredClaimNames.Sub, tokenRequest.ClientId), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, _tokenOpts.IssuedAtAsUnixEpoch.ToString(), ClaimValueTypes.Integer64), }, _tokenOpts.NotBefore, _tokenOpts.Expiration, _tokenOpts.SigningCredentials ); return(true, new JwtSecurityTokenHandler().WriteToken(jwtToken)); }
public bool IsAuthenticated(AuthTokenRequest request, out string token) { token = string.Empty; if (!_userManagementService.IsValidUser(request.Username, request.Password).AwaitResult <bool>()) { return(false); } var claims = new [] { new Claim(ClaimTypes.Name, request.Username) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenSettings.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken( _tokenSettings.Issuer, _tokenSettings.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenSettings.AccessExpiration), signingCredentials: credentials ); token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="Account" /> class. /// </summary> /// <param name="cloudApi"></param> /// <param name="login">Login name as email.</param> /// <param name="password">Password related with this login</param> /// <param name="twoFaHandler"></param> public Account(CloudApi cloudApi, string login, string password, ITwoFaHandler twoFaHandler) { _cloudApi = cloudApi; LoginName = login; Password = password; WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials; Proxy = WebRequest.DefaultWebProxy; var twoFaHandler1 = twoFaHandler; if (twoFaHandler1 != null) { AuthCodeRequiredEvent += twoFaHandler1.Get; } _bannedShards = new Cached <List <ShardInfo> >(() => new List <ShardInfo>(), TimeSpan.FromMinutes(4)); _cachedShards = new Cached <Dictionary <ShardType, ShardInfo> >(() => new ShardInfoRequest(_cloudApi).MakeRequestAsync().Result.ToShardInfo(), TimeSpan.FromSeconds(ShardsExpiresInSec)); DownloadToken = new Cached <string>(() => new DownloadTokenRequest(_cloudApi).MakeRequestAsync().Result.ToToken(), TimeSpan.FromSeconds(DownloadTokenExpiresSec)); AuthToken = new Cached <string>(() => { Logger.Debug("AuthToken expired, refreshing."); var token = new AuthTokenRequest(_cloudApi).MakeRequestAsync().Result.ToToken(); DownloadToken.Expire(); return(token); }, TimeSpan.FromSeconds(AuthTokenExpiresInSec)); }
public async Task AuthToken_Generate_Failed_missing_phone_and_Password() { //arrange _authTokenAPI = new AuthTokenController(new AuthTokenService(_authTokenRepositoryMock.Object, _personsRepositoryMock.Object)) { Request = new System.Net.Http.HttpRequestMessage(), Configuration = new HttpConfiguration() }; var authTokenRequest = new AuthTokenRequest() { Phone = "", Password = "" }; _personsRepositoryMock.Setup(x => x.IsPhoneExists(It.IsAny <string>())).Returns(true); _authTokenRepositoryMock.Setup(x => x.Add(It.IsAny <AuthToken>())).Returns(It.IsAny <int>()); //act var response = await _authTokenAPI.GenerateAsync(authTokenRequest); var responseBody = await Task.FromResult(response.Content.ReadAsStringAsync()).Result; //assert Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, response.StatusCode); Assert.IsTrue(responseBody.Contains("{\\\"MemberNames\\\":[\\\"Password\\\"],\\\"ErrorMessage\\\":\\\"blank\\\"}")); Assert.IsTrue(responseBody.Contains("{\\\"MemberNames\\\":[\\\"Phone\\\"],\\\"ErrorMessage\\\":\\\"blank\\\"}")); }
/// <summary> /// Make a call to /auth/token /// </summary> /// <param name="clientId">20 character long external client ID.</param> /// <param name="clientSecret">64 character long external client secret.</param> /// <param name="code">20 character long OAuth authorization grant code returned from auth/prompt redirection.</param> /// <param name="redirectUri">URL that was provided at the time of external client registration.</param> /// <returns></returns> public AccessToken GetAccessToken(string clientId, string clientSecret, string code, string redirectUri) { var req = new AuthTokenRequest(clientId, clientSecret, code, redirectUri, _Settings); WireBeforeRequestEvents(req); WireAfterRequestEvents(req); return(req.GetAccessToken()); }
public async Task <AuthTokenResponse> Generate([FromBody] AuthTokenRequest request) { this.ValidateRequest(request); var vkCheckToken = await _vKAuthService.CheckVkToken(request.Token); //var token = await _authService.Generate(vkCheckToken.); return(vkCheckToken); }
public Result <AuthTokenResponse> GetToken( [Body] AuthTokenRequest request ) { var auth = Service <IAuthService>(); var grantType = request.GrantType; if (grantType == "client_credentials") { if (TokenAuthClient("auth_token_client_credentials", request.ClientId, request.ClientSecret, out Guid? clientId, out Result <AuthTokenResponse> authClientResult)) { if (auth.AuthenticateClientScope(clientId.Value, request.Scope, out Guid[] validScope))
public ActionResult <ApiDataResponse <AuthTokenResponse> > RequestToken([FromBody] AuthTokenRequest request) { var(authenticatedSuccessfully, token) = jwtService.IssueToken(request); return(authenticatedSuccessfully ? ApiResponse.ForData( new AuthTokenResponse(token), "Access token issued successfully.") : ApiResponse.ForData( new AuthTokenResponse(), "An invalid or unauthorized Client ID was provided.", StatusCodes.Status401Unauthorized)); }
public TokenResponse RequestAuthToken(AuthTokenRequest tokenRequest) { if (tokenRequest == null) { throw new ArgumentNullException(nameof(tokenRequest)); } if (tokenRequest.Registration == null) { throw new ArgumentException("No directory registration specified.", nameof(tokenRequest.Registration)); } if (string.IsNullOrWhiteSpace(tokenRequest.CallbackUrl)) { throw new ArgumentException("No callback url specified.", nameof(tokenRequest.CallbackUrl)); } if (string.IsNullOrWhiteSpace(tokenRequest.RequestCode)) { throw new ArgumentException("No requests code specified", nameof(tokenRequest.RequestCode)); } if (tokenRequest?.Scopes.Any() == false) { throw new ArgumentException("No scopes provided", nameof(tokenRequest.Scopes)); } var postData = $"grant_type=authorization_code&redirect_uri={tokenRequest.CallbackUrl.UrlEncode()}&code={tokenRequest.RequestCode}&client_id={tokenRequest.Registration.ClientId}&client_secret={tokenRequest.Registration.ClientSecret.UrlEncode()}&scope={BuildScopesFragment(tokenRequest.Scopes)}"; var result = MsGraph.TokenUrl.PostToUrl(postData); var authInfo = JsonObject.Parse(result); var authInfoNvc = authInfo.ToNameValueCollection(); if (MsGraph.RespondedWithError(authInfoNvc)) { throw new AzureServiceException(MsGraph.TokenUrl, authInfoNvc); } return(new TokenResponse { AuthData = authInfoNvc, AccessToken = authInfo["access_token"], RefreshToken = authInfo["refresh_token"], IdToken = authInfo["id_token"], TokenExpirationSeconds = authInfo["expires_in"] }); }
public ActionResult Token([FromBody] AuthTokenRequest request) { if (!ModelState.IsValid) { return(BadRequest("Invalid Request")); } if (_authService.IsAuthenticated(request, out string token)) { return(Ok(token)); } else { return(Unauthorized()); } }
public async Task <string> GetBearerToken(string clientId, string secret) { HttpClient client = new HttpClient(); string uri = "https://app.load1.com/api/graphql/auth/token"; var authenticateRequest = new AuthTokenRequest { ClientID = clientId, ClientSecret = secret }; var content = new StringContent(JsonConvert.SerializeObject(authenticateRequest), Encoding.UTF8, "application/json"); var response = await client.PostAsync(uri, content); response.EnsureSuccessStatusCode(); var authTokenResponse = JsonConvert.DeserializeObject <AuthTokenResponse>(await response.Content.ReadAsStringAsync()); return(authTokenResponse.Access_Token); }
public TokenResponse RequestAuthToken(AuthTokenRequest tokenRequest) { var idToken = TokenHelper.GetIdToken(); var nvc = new NameValueCollection { { "access_token", TokenHelper.AccessToken }, { "id_token", idToken } }; TokenHelper.HydrateAuthInfo(idToken, nvc); return(new TokenResponse { AccessToken = TokenHelper.AccessToken, RefreshToken = TokenHelper.RefreshToken, AuthData = nvc }); }
protected async Task <string> GetAuthTokenAsync() { try { if (string.IsNullOrEmpty(authToken)) { var plainText = new StringFactory(); var authRequest = new AuthTokenRequest(AzureRegion, azureSubscriptionKey); authToken = await authRequest.DecodeAsync(plainText) .ConfigureAwait(false); } return(authToken); } catch { IsAvailable = false; throw; } }
public async Task CreateToken() { var content = new AuthTokenContent { GrantType = AuthTokenRequest.authorization_code }; var arg = new AuthTokenArg { AppId = config.AppId, BizContent = content }; arg.SetRSA2Sign(@"D:\Programing\Dev Repos\ZeusPay\alipayPrivateKey.txt"); var client = new AlipayClient(); var result = await AuthTokenRequest.Request(client, arg); Assert.IsNotNull(result); if (result != null) { Assert.AreEqual(result.AlipayTradePrecreateResponse.Code, 10000); } }
public async Task <AuthTokenResponse> GenerateYoutube([FromBody] AuthTokenRequest request) { try { Serilog.Log.Logger.Information(request.ChannalId + " - " + request.Token); this.ValidateRequest(request); Serilog.Log.Logger.Information("ValidateRequest"); var vkCheckToken = await _vKAuthService.CheckGoogleAuthToken(request.Token, request.ChannalId); Serilog.Log.Logger.Information("CheckGoogleAuthToken"); return(vkCheckToken); } catch (Exception ex) { Serilog.Log.Logger.Error(ex, "[ {NewLine} {Timestamp} {SourceContext} {Level:u4}] {Message} {NewLine} {Exception} {NewLine}"); if (ex.InnerException != null) { Serilog.Log.Logger.Error(ex.InnerException, "[ {NewLine} {Timestamp} {SourceContext} {Level:u4}] {Message} {NewLine} {Exception} {NewLine}"); } throw; } }
public async Task AuthToken_Generate_Success() { //arrange _authTokenAPI = new AuthTokenController(new AuthTokenService(_authTokenRepositoryMock.Object, _personsRepositoryMock.Object)) { Request = new System.Net.Http.HttpRequestMessage(), Configuration = new HttpConfiguration() }; var authTokenRequest = new AuthTokenRequest() { Phone = "123456789123", Password = "******" }; _personsRepositoryMock.Setup(x => x.IsPhoneExists(It.IsAny <string>())).Returns(true); _authTokenRepositoryMock.Setup(x => x.Add(It.IsAny <AuthToken>())).Returns(It.IsAny <int>()); //act var response = await _authTokenAPI.GenerateAsync(authTokenRequest); //assert Assert.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode); }
public AuthTokenModel Execute(AuthTokenRequest request) { return(new AuthTokenModel { }); }
/// <summary> /// Authenticate request. /// </summary> public AuthTokenResponse Authenticate(AuthTokenRequest request, out string error) { error = null; AuthTokenResponse info = null; var grantType = request.GrantType; if (grantType == "client_credentials") { #region client_credentials var base64ClientId = request.ClientId; var base64ClientSecret = request.ClientSecret; string strClientId = Base64.UrlDecode(base64ClientId); //var clientId = Guid.TryParse(strClientId); //if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) //{ // error = "invalid_grant"; // errorDescription = "username and password are required"; //} //else //{ // var id = sql.Select("ident", "id_id", "id_password", "id_salt"); // id.Where = (SqlColumn)"id_name" == username; // var r = id.Execute(); // if (r.First.Count == 1) // { // var ro = r.First.First; // var spass = ro["id_password"].GetByteArray(); // var ssalt = ro["id_salt"].GetByteArray(); // if (spass == null || ssalt == null) // { // error = "invalid_request"; // errorDescription = "server:spass_ssalt_null"; // } // else // { // var hash = Hash.SHA512(ssalt.Concat(password.ToBytes())); // if (!hash.SequenceEqual(spass)) // { // error = "invalid_grant"; // errorDescription = "invalid username or password"; // } // else // { // info = CreateAuthInfo(ro["id_id"].GetGuid()); // } // } // } // else // { // error = "invalid_grant"; // errorDescription = "invalid username or password"; // } #endregion } else if (string.IsNullOrEmpty(grantType)) { error = "invalid_grant"; } else { error = "unsupported_grant_type"; } return(info); }
public AuthTokenModel Execute(AuthTokenRequest request) { return new AuthTokenModel {}; }
public async Task <AuthTokenResponse> GenerateAsync([FromBody] AuthTokenRequest authTokenRequest) { var response = await _tokenService.CreateAsync(authTokenRequest.UserId); return(response.ToDataContract()); }