public SpotifyAuthentication(IConfiguration configuration) { this.clientId = configuration["Spotify:ClientId"]; this.clientSecret = configuration["Spotify:ClientSecret"]; this.redirectUri = configuration["Spotify:RedirectUri"]; this.parameters = new AuthParameters { ClientId = this.clientId, ClientSecret = this.clientSecret, RedirectUri = this.redirectUri, Scopes = Scopes.All, ShowDialog = true }; }
public void RegisterSameUser() { // Arrange var password = "******"; var passwordHash = Encrypter.EncryptString(password, KEY); var client = new Client(Guid.NewGuid(), 1, passwordHash, "Wall Disney"); var authParameters = new AuthParameters(client.Login, password); var mockClientRepository = new Mock <IClientRepository>(); mockClientRepository.Setup(repo => repo.Insert(It.IsAny <Client>())).Returns(client); mockClientRepository.Setup(repo => repo.GetByLoginAsync(It.IsAny <string>())).Returns(Task.FromResult(client)); var authService = new AuthService(mockClientRepository.Object); // Assert Assert.Throws <UserExistException>(() => authService.Register(authParameters)); }
public async Task <bool> LoginAsync(string userName, string password) => (await OAuthClient.GetAccessToken(userName, password)) .OnFailure(result => { GetAccessTokenFailed?.Invoke(result.Error); _authParameters = AuthParameters.Empty; }) .OnSuccess(result => GetAccessTokenSucceed?.Invoke(result.Value.AccessToken.Value)) .OnSuccess(result => _authParameters = AuthParameters.Create( accessToken: result.Value.AccessToken.Value, accessTokenExpiration: result.Value.AccessToken.ExpireInSeconds, refreshToken: result.Value.RefreshToken.Value)) .OnSuccess(() => { _refreshCancellationTokenSource = new CancellationTokenSource(); BeginTokenRefreshLoop(_refreshCancellationTokenSource.Token); }).IsSuccess;
public void AuthWithWrongPassword() { // Arrange var password = "******"; var passwordHash = Encrypter.EncryptString(password, KEY); var client = new Client(Guid.NewGuid(), 1, new Role { Name = "Admin", RoleId = 1 }, passwordHash, "Wall Disney"); var authParameters = new AuthParameters(client.Login, "253532"); var mockClientRepository = new Mock <IClientRepository>(); mockClientRepository.Setup(repo => repo.GetByLogin(It.IsAny <string>())).Returns(client); var authService = new AuthService(mockClientRepository.Object); // Act Assert.Throws <WrongPasswordException>(() => authService.Auth(authParameters)); }
private void pay_Click(object sender, RoutedEventArgs e) { if (result.Text.Length > 7) { txtResponse.Text = "Invalid Amount."; } else { txtResponse.Text = "Processing ..."; PaymentManager mgr = PaymentManager.Instance; mgr.setPaymentResponseListener(this); AuthParameters parameters = new AuthParameters(); parameters.amount = result.Text.Trim(); parameters.amountOther = "0"; parameters.isQuickChip = false; parameters.transactionOption = TRANSACTION_OPTION.Purchase; parameters.transactionMethod = PaymentSDK.ChecoutServiceReference.TransactionMethod.MSR_EMV_CL; #if (SHIFT4) Shift4AuthParameters gwparams = new Shift4AuthParameters(); gwparams.customerReference = ""; gwparams.destinationPostalCode = ""; gwparams.invoice = ""; //gwparams.surcharge = ""; gwparams.tax = Settings.tax; gwparams.tip = Settings.tip; ObservableCollection <string> ob = new ObservableCollection <string>(); ob.Add("salmon"); ob.Add("tuna"); gwparams.productDescriptors = ob; parameters.gateWayParameters = gwparams; #endif #if (CREDITCALL) //Nothing required from cc prespective #endif mgr.Pay(parameters); Settings.tax = null; Settings.tip = null; } }
public string RefreshAuthorizationData(AuthParameters authParameters) { if (!String.IsNullOrEmpty(authParameters.Error)) { throw new Exception(authParameters.Error); } // make sure we have the necessary parameters ValidateParameter("storeUrl", authParameters.ServerUrl); ValidateParameter("clientId", authParameters.ClientId); ValidateParameter("GrantType", authParameters.GrantType); ValidateParameter("RefreshToken", authParameters.RefreshToken); // get the access token string accessToken = _apiAuthorizer.RefreshToken(authParameters.RefreshToken, authParameters.GrantType); return(accessToken); }
public ActionResult Post([FromBody] AuthParameters login) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var identity = _authService.Auth(login); if (identity == null) { return(BadRequest("Invalid username or password.")); } var token = JWTTokenGenerator.GenerateJSWToken(identity); return(Ok(new { Token = token })); }
private PlaylistTrack getSongFromApi() { var param = new AuthParameters { Scopes = Scope.All, ClientId = SettingsLoader.SettingsContainer.Spotify_Client_Id, ClientSecret = SettingsLoader.SettingsContainer.Spotify_Client_Secret, RedirectUri = "http://google.com", ShowDialog = false, // Set to true to login each time. }; var token = ClientCredentials.GetToken(param); ISpotifyWebApi api = new SpotifyWebApi.SpotifyWebApi(token); FullPlaylist playlist = api.Playlist.GetPlaylist(SpotifyUri.Make("spotify:user:1189618539:playlist:03gha5BWxoJ17xtn3FOvyl")).Result; return(playlist.Tracks.Items.OrderBy(x => Guid.NewGuid()).FirstOrDefault()); }
public void EnsureValidParameters(AuthParameters parameters) { HandleErrors(nameof(EnsureValidParameters), () => { var validResopnseTypes = Consts.Oidc.ValidResponseTypes; if (parameters.AuthorizationEndpoint.IsEmpty()) { throw Logger.Exception("No Authorization Endpoint passed"); } if (parameters.ClientId.IsEmpty()) { throw Logger.Exception("No ClientId passed"); } if (parameters.RedirectUri.IsEmpty()) { throw Logger.Exception("No RedirectUri passed"); } if (parameters.ResponseType.IsEmpty()) { throw Logger.Exception("No ResponseType passed"); } if (parameters.Scope.IsEmpty()) { throw Logger.Exception("No Scope passed"); } if (parameters.Issuer.IsEmpty()) { throw Logger.Exception("No Issuer passed"); } if (!validResopnseTypes.Any(x => x.Equals(parameters.ResponseType))) { throw Logger.Exception("Response type must be " + string.Join(" OR ", validResopnseTypes)); } if (Settings.StorageType.IsMemory() && parameters.InteractionType.IsRedirect()) { throw Logger.Exception("Interaction type cannot be redirect using memory storage"); } }); }
public void RegistrationTest() { // Arrange var password = "******"; var passwordHash = Encrypter.EncryptString(password, KEY); var client = new Client(Guid.NewGuid(), 1, passwordHash, "Wall Disney"); var authParameters = new AuthParameters(client.Login, password); var mockClientRepository = new Mock <IClientRepository>(); mockClientRepository.Setup(repo => repo.Insert(It.IsAny <Client>())).Returns(client); var authService = new AuthService(mockClientRepository.Object); // Act var result = authService.Register(authParameters); // Assert Assert.Equal(client.Login, result.Login); Assert.Equal(client.PasswordHash, result.PasswordHash); Assert.Equal(client.RoleId, result.RoleId); }
public void AuthWithNotExistUser() { // Arrange var password = "******"; var passwordHash = Encrypter.EncryptString(password, KEY); var client = new Client(Guid.NewGuid(), 1, new Role { Name = "Admin", RoleId = 1 }, passwordHash, "Wall Disney"); var authParameters = new AuthParameters(client.Login, password); var mockClientRepository = new Mock <IClientRepository>(); mockClientRepository.Setup(repo => repo.GetByLogin(It.IsAny <string>())).Returns((Client)null); var authService = new AuthService(mockClientRepository.Object); // Act var result = authService.Auth(authParameters); // Assert Assert.Null(result); }
/// <summary> /// Main entry point. /// </summary> /// <param name="args">Command line arguments.</param> public static void Main(string[] args) { var param = new AuthParameters { Scopes = Scope.All, ClientId = ConfigurationManager.AppSettings["clientId"], ClientSecret = ConfigurationManager.AppSettings["clientSecret"], RedirectUri = ConfigurationManager.AppSettings["redirectUri"], ShowDialog = false, // Set to true to login each time. }; //var url = AuthorizationCode.GetUrl(param, "test"); //Process.Start(url); //var r = GetResponse().GetAwaiter().GetResult(); //var token = AuthorizationCode.ProcessCallback(param, r, string.Empty); var token = ClientCredentials.GetToken(param); ISpotifyWebApi api = new SpotifyWebApi(token); var task1 = api.UserProfile.GetMe(); var task2 = api.Player.GetCurrentlyPlayingContext(); var task3 = api.Playlist.GetMyPlaylists(200); Task.WhenAll(task1, task2, task3).GetAwaiter().GetResult(); var me = task1.Result; var t = task2.Result; var p = task3.Result; Console.WriteLine($"Hello {me.DisplayName}, This is an example application!"); Console.WriteLine($"You are listening to {t.Item.Name} on {t.Device.Name}"); foreach (var simplePlaylist in p) { Console.WriteLine($"{simplePlaylist.Id}, {simplePlaylist.Name}"); } Console.ReadLine(); }
private void BeginTokenRefreshLoop(CancellationToken ct) { _loopReference = Task.Run(async() => { TokenRefreshLoopStatusChanged?.Invoke(RefreshLoopStatus.Started, LoopTimeout); try { while (true) { await Task.Delay(LoopTimeout, ct); (await RefreshAccessToken(_authParameters.RefreshToken)) .OnSuccess(() => TokenRefreshLoopStatusChanged?.Invoke(RefreshLoopStatus.Running, LoopTimeout)) .OnSuccess(result => { _authParameters = result.Value; GetAccessTokenSucceed?.Invoke($"Access Token Refreshed: {result.Value.AccessToken}"); }) .OnFailure(result => { GetAccessTokenFailed?.Invoke(result.Error); _refreshCancellationTokenSource.Cancel(); }); } } catch (OperationCanceledException) { //no-op: refresh loop manually stopped, all ok. } catch (Exception exception) { GetAccessTokenFailed?.Invoke(exception.Message); _refreshCancellationTokenSource.Cancel(); } finally { TokenRefreshLoopStatusChanged?.Invoke(RefreshLoopStatus.Stopped, LoopTimeout); } }, ct); }
private static string Signature() { if (authParams == null) { authParams = AuthorizationController.GetAuthParams(); } if (String.IsNullOrWhiteSpace(authParams.SecretToken) || String.IsNullOrWhiteSpace(authParams.PublicToken)) { return(""); } string signature; var secretBytes = Encoding.UTF8.GetBytes(authParams.SecretToken); var valueBytes = Encoding.UTF8.GetBytes(authParams.PublicToken); using (var hmac = new HMACSHA256(secretBytes)) { var hash = hmac.ComputeHash(valueBytes); signature = Convert.ToBase64String(hash); } return(signature); }
public override async Task <IAuthenticatonResult> Authenticate(AuthParameters authParameters) { try { WebAuthenticatorResult authApiResultData = null; var authUrl = new Uri(config.AuthApiSettings.socialAuthEndPoint + authParameters.AuthType.ToString()); var callbackUrl = new Uri("xamarinessentials://"); authApiResultData = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl); var user = new Models.User.User_Model(); user.Name = authApiResultData.Properties["name"] ?? "Unknown"; return(new AuthResult(AuthStatus.Success, "", authApiResultData.AccessToken, authApiResultData.RefreshToken, authApiResultData.ExpiresIn, user)); } catch (Exception ex) { await logger.LogToDebugger(ex.Message); return(new AuthResult(AuthStatus.Error, ex.Message)); } }
private void btnAuth_Click(object sender, RoutedEventArgs e) { txtResponse.Text = "Processing ..."; PaymentManager mgr = PaymentManager.Instance; mgr.setPaymentResponseListener(this); AuthParameters authParameters = new AuthParameters(); authParameters.amount = result.Text.Trim(); authParameters.amountOther = "0"; authParameters.transactionOption = TRANSACTION_OPTION.Purchase; authParameters.transactionMethod = PaymentSDK.ChecoutServiceReference.TransactionMethod.MSR_EMV_CL; #if (SHIFT4) Shift4AuthParameters parameters = new Shift4AuthParameters(); parameters.customerReference = ""; parameters.destinationPostalCode = ""; parameters.surcharge = ""; parameters.tax = Settings.tax; parameters.tip = Settings.tip; ObservableCollection <string> ob = new ObservableCollection <string>(); ob.Add("salmon"); ob.Add("tuna"); parameters.productDescriptors = ob; authParameters.gateWayParameters = parameters; #endif #if (CREDITCALL) // No special parameter required for CreditCall in this case #endif mgr.Auth(authParameters); }
private void Form1_Load(object sender, EventArgs e) { OptionsMercator repMerc = new OptionsMercator(); OptionsMercator journal = new OptionsMercator(); string repMercValue = repMerc.GetOptionValue("NOP_REP_M")?.ToString(); string journalValue = journal.GetOptionValue("NOP_JOURN")?.ToString(); txtRepMercator.Text = repMercValue?.ToString()?.TrimEnd() ?? ""; txtJournal.Text = journalValue?.ToString()?.TrimEnd() ?? ""; if (DatabaseManager.CheckTableExistence("WEB_API_CREDENTIALS")) { AuthParameters ap = AuthorizationController.GetAuthParams(); if (ap != null) { txtPublicToken.Text = ap.PublicToken; txtSecretToken.Text = ap.SecretToken; txtStoreAddress.Text = ap.StoreAddress; txtUser.Text = ap.ClientName; } } }
public ClaimsIdentity Auth(AuthParameters user) { var person = _clientRepository.GetByLogin(user.Login); if (person == null) { return(null); } var personPassord = Encrypter.DecryptString(person.PasswordHash, KEY); if (user.Password != personPassord) { throw new WrongPasswordException(); } var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, person.Login), new Claim(ClaimsIdentity.DefaultRoleClaimType, person.Role.Name) }; return(new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType)); }
private string BuildAuthenticationUrl(AuthParameters parameters, AuthState state) { return(new UrlBuilder(parameters.AuthorizationEndpoint) .Add("scope", parameters.Scope) .Add("response_type", parameters.ResponseType) .Add("client_id", parameters.ClientId) .Add("redirect_uri", parameters.RedirectUri) .Add("state", state.State) .Add("response_mode", parameters.ResponseMode) .Add("display", parameters.Display.Format()) .Add("prompt", parameters.Prompt.Format()) .Add("max_age", parameters.MaxAge.HasValue ? parameters.MaxAge.ToString() : null) .Add("ui_locales", parameters.UiLocales) .Add("id_token_hint", parameters.IdTokenHint) .Add("login_hint", parameters.LoginHint) .Add("resource", parameters.Resource) .Add("request", parameters.Request) .Add("request_uri", parameters.RequestUri) .Add("nonce", state.Nonce, parameters.RequiresNonce) .Add("code_challenge", state.CodeChallenge, parameters.RequiresCodeVerifier) .Add("code_challenge_method", "S256", parameters.RequiresCodeVerifier) .Add(parameters.AdditionalParameters) .ToString()); }
private InventoryService(AuthInfo authInfo, AuthParameters authParameters) { _authParameters = authParameters; _authInfo = authInfo; }
public override async Task <IAuthenticatonResult> RefreshAuthentication(AuthParameters authParameters) { throw new NotImplementedException(); }
private ProductService(AuthInfo authInfo, AuthParameters authParameters) { _authParameters = authParameters; _authInfo = authInfo; }
private OrderService(AuthInfo authInfo, AuthParameters authParameters) { _authParameters = authParameters; _authInfo = authInfo; }
private void button2_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtUser.Text)) { txtUser.Text = "Remplissez ce champ!"; txtUser.ForeColor = Color.Red; return; } if (String.IsNullOrEmpty(txtPublicToken.Text)) { txtPublicToken.Text = "Remplissez ce champ!"; txtPublicToken.ForeColor = Color.Red; return; } if (String.IsNullOrEmpty(txtSecretToken.Text)) { txtSecretToken.Text = "Remplissez ce champ!"; txtSecretToken.ForeColor = Color.Red; return; } if (String.IsNullOrEmpty(txtStoreAddress.Text)) { txtStoreAddress.Text = "Remplissez ce champ!"; txtStoreAddress.ForeColor = Color.Red; return; } if (String.IsNullOrEmpty(txtJournal.Text)) { txtJournal.Text = "Remplissez ce champ!"; txtJournal.ForeColor = Color.Red; return; } if (String.IsNullOrEmpty(txtRepMercator.Text)) { txtRepMercator.Text = "Remplissez ce champ!"; txtRepMercator.ForeColor = Color.Red; return; } AuthorizationController controller = new AuthorizationController(); DataSettings ds = DatabaseManager.LoadSettings(); //AuthParameters authParams = controller.InitiateAuthorization(txtServerUrl.Text,txtClientId.Text,txtClientSecret.Text); InstallerDatas install = new InstallerDatas(); install.JournalMercator = txtJournal.Text; install.RepMercator = txtRepMercator.Text; install.ConnectionString = ds.DataConnectionString; AuthParameters authParams = new AuthParameters(); authParams.ClientName = txtUser.Text; authParams.PublicToken = txtPublicToken.Text; authParams.SecretToken = txtSecretToken.Text; authParams.StoreAddress = txtStoreAddress.Text; install.authParameters = authParams; InstallerProgressBar installPB = new InstallerProgressBar(install); installPB.Show(); this.Hide(); }
public ActionResult GetAccessToken(string code, string state) { if (ModelState.IsValid && !string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state)) { if (state != HttpContext.Session.GetString("state")) { return(BadRequest()); } var model = new AccessModel(); try { // TODO: Here you should get the authorization user data from the database instead from the current Session. string clientId = HttpContext.Session.GetString("clientId"); string clientSecret = HttpContext.Session.GetString("clientSecret"); string serverUrl = HttpContext.Session.GetString("serverUrl"); string redirectUrl = HttpContext.Session.GetString("redirectUrl"); var authParameters = new AuthParameters() { ClientId = clientId, ClientSecret = clientSecret, ServerUrl = serverUrl, RedirectUrl = redirectUrl, GrantType = "authorization_code", Code = code }; var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId, authParameters.ClientSecret, authParameters.ServerUrl); string responseJson = nopAuthorizationManager.GetAuthorizationData(authParameters); AuthorizationModel authorizationModel = JsonConvert.DeserializeObject <AuthorizationModel>(responseJson); model.AuthorizationModel = authorizationModel; model.UserAccessModel = new UserAccessModel() { ClientId = clientId, ClientSecret = clientSecret, ServerUrl = serverUrl, RedirectUrl = redirectUrl }; var authorizationModelConverted = JsonConvert.SerializeObject(authorizationModel.AccessToken); // TODO: Here you can save your access and refresh tokens in the database. For illustration purposes we will save them in the Session and show them in the view. HttpContext.Session.SetString("accessToken", authorizationModel.AccessToken); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"auth.txt", true)) { file.WriteLine(authorizationModel.AccessToken); file.WriteLine(authParameters.ServerUrl); } TempData["accessToken"] = authorizationModel.AccessToken; TempData["serverUrl"] = serverUrl; } catch (Exception ex) { return(BadRequest(ex.Message)); } return(View("~/Views/AccessToken.cshtml", model)); } return(BadRequest()); }
private async Task <Result <AuthParameters> > RefreshAccessToken(string refreshToken) => (await OAuthClient.RefreshAccessToken(refreshToken)) .Map(result => AuthParameters.Create( accessToken: result.AccessToken.Value, accessTokenExpiration: result.AccessToken.ExpireInSeconds, refreshToken: result.RefreshToken.Value));
public Task LogoutAsync() { _refreshCancellationTokenSource.Cancel(); _authParameters = AuthParameters.Empty; return(Task.CompletedTask); }
public async Task <ActionResult <UserAuthModel> > PostToken(AuthParameters authParameters) { var authToken = await _authService.ExchangeCodeForToken(authParameters); return(Ok(authToken)); }