public async Task <IActionResult> Signin([FromBody] TokenRequest request) { var result = new ApiResponse <CredentialResponse>(); if (!ModelState.IsValid) { result.AddError(ModelState); return(Ok(result)); } var authWithToken = await authneticateService.IsAuthenticatedAsync(request); if (authWithToken.IsAuthenticated) { var credentialReponse = new CredentialResponse { Token = authWithToken.Token }; result.AddData(credentialReponse); return(Ok(result)); } result.AddError("Invalid Account"); return(Ok(result)); }
public Task <CredentialResponse> GetAsync( Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (nonInteractive) { return(Task.FromResult( new CredentialResponse(null, CredentialStatus.ProviderNotApplicable))); } switch (type) { case CredentialRequestType.Proxy: message = LocalizedResourceManager.GetString("Credentials_ProxyCredentials"); break; case CredentialRequestType.Forbidden: message = LocalizedResourceManager.GetString("Credentials_ForbiddenCredentials"); break; default: message = LocalizedResourceManager.GetString("Credentials_RequestCredentials"); break; } Console.WriteLine(message, uri.OriginalString); Console.Write(LocalizedResourceManager.GetString("Credentials_UserName")); cancellationToken.ThrowIfCancellationRequested(); string username = Console.ReadLine(); Console.Write(LocalizedResourceManager.GetString("Credentials_Password")); using (SecureString password = new SecureString()) { cancellationToken.ThrowIfCancellationRequested(); Console.ReadSecureString(password); var credentials = new NetworkCredential { UserName = username, SecurePassword = password }; var cred = new CredentialResponse(credentials, CredentialStatus.Success); var task = Task.FromResult(cred); return(task); } }
public static string LoginGameUser(string u, string p) { //do actual login var cr = new CredentialResponse(); cr.UserName = u; cr.Token = new List <int>(new int[] { 1, 5, 6, 7, 8, 9, 5 });//little static currently var jss = new JavaScriptSerializer(); return(jss.Serialize(cr)); }
private bool TryFromCredentialCache(Uri uri, CredentialRequestType type, bool isRetry, ICredentialProvider provider, out CredentialResponse credentials) { credentials = null; var key = CredentialsKeyHelper.GetCacheKey(uri, type, provider); if (isRetry) { CredentialResponse removed; _providerCredentialCache.TryRemove(key, out removed); return(false); } return(_providerCredentialCache.TryGetValue(key, out credentials)); }
public async Task <CredentialResponse> GetAsync(Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken) { if (isRetry) { Log.Debug($"Retrying to request credentials for '{uri}'"); } else { Log.Debug($"Requesting credentials for '{uri}'"); } bool?result = null; var uriString = uri.ToString().ToLower(); var credentialsPrompter = new CredentialsPrompter(_configurationService) { Target = uriString, AllowStoredCredentials = !isRetry && _canAccessStoredCredentials, ShowSaveCheckBox = true, WindowTitle = "Credentials required", MainInstruction = "Credentials are required to access this feed", Content = message, IsAuthenticationRequired = true }; result = credentialsPrompter.ShowDialog(); if (result ?? false) { //creating success response Log.Debug("Successfully requested credentials for '{0}' using user '{1}'", uri, credentialsPrompter.UserName); //creating network credentials var nugetCredentials = new NetworkCredential(credentialsPrompter.UserName, credentialsPrompter.Password); var response = new CredentialResponse(nugetCredentials); return(response); } else { Log.Debug("Failed to request credentials for '{0}'", uri); return(new CredentialResponse(CredentialStatus.UserCanceled)); } }
/// <summary> /// Returns an ICredentials instance that the consumer would need in order /// to properly authenticate to the given Uri. /// </summary> public async Task <CredentialResponse> GetAsync( Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } // Capture the original proxy before we do anything // so that we can re-set it once we get the credentials for the given Uri. IWebProxy originalProxy = null; if (proxy != null) { // If the current Uri should be bypassed then don't try to get the specific // proxy but simply capture the one that is given to us if (proxy.IsBypassed(uri)) { originalProxy = proxy; } // If the current Uri is not bypassed then get a valid proxy for the Uri // and make sure that we have the credentials also. else { originalProxy = new WebProxy(proxy.GetProxy(uri)); originalProxy.Credentials = proxy.Credentials == null ? null : proxy.Credentials.GetCredential(uri, null); } } try { // The cached credentials that we found are not valid so let's ask the user // until they abort or give us valid credentials. var uriToDisplay = uri; if (type == CredentialRequestType.Proxy && proxy != null) { // Display the proxy server's host name when asking for proxy credentials uriToDisplay = proxy.GetProxy(uri); } // Set the static property WebRequest.DefaultWebProxy so that the right host name // is displayed in the UI by IVsWebProxy. Note that this is just a UI thing, // so this is needed no matter wether we're prompting for proxy credentials // or request credentials. WebRequest.DefaultWebProxy = new WebProxy(uriToDisplay); var cred = await PromptForCredentials(uri, cancellationToken); var response = new CredentialResponse(cred, CredentialStatus.Success); return(response); } finally { // Reset the original WebRequest.DefaultWebProxy to what it was when we started credential // discovery. WebRequest.DefaultWebProxy = originalProxy; } }
/// <summary> /// Determines if the endpoint is a Visual Studio Online endpoint. If so, uses the keychain to get a /// session token for the endpoint and returns that as a ICredentials object /// </summary> /// <param name="uri">URI for the feed endponint to use</param> /// <param name="proxy">Web proxy to use when comunicating on the network. Null if there is no proxy /// authentication configured</param> /// <param name="type"> /// The type of credential request that is being made. Note that this implementation of /// <see cref="ICredentialProvider"/> does not support providing proxy credenitials and treats /// all other types the same. /// </param> /// <param name="message">A message provided by NuGet to show to the user when prompting.</param> /// <param name="isRetry">Flag to indicate if this is the first time the URI has been looked up. /// If this is true we check to see if the account has access to the feed. /// First time we assume that is true to minimize network trafic.</param> /// <param name="nonInteractive">Flag to indicate if UI can be shown. If true, we will fail in cases /// where we need to show UI instead of prompting</param> /// <param name="cancellationToken">Cancelation token used to comunicate cancelation to the async tasks</param> /// <returns>If a credentials can be obtained a credentails object with a session token for the URI, /// if not NULL</returns> public async Task <CredentialResponse> GetAsync( Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!InteractiveLoginProvider.IsValidScheme(uri)) { // We are not talking to a https endpoint so it cannot be a VSO endpoint return(new CredentialResponse(CredentialStatus.ProviderNotApplicable)); } if (type == CredentialRequestType.Proxy) { // We don't handle getting proxy credentials so don't try to do anything on a isProxyRequest. return(new CredentialResponse(CredentialStatus.ProviderNotApplicable)); } var posibleAccounts = new List <AccountAndTenant>(); // Check to see if this is a VSO endpoint before we do anything else var uriTenantId = await _loginProvider.LookupTenant(uri, proxy, cancellationToken); if (string.IsNullOrWhiteSpace(uriTenantId)) { // we don't have a tenant ID so this cannot be a VSO endpoint return(new CredentialResponse(CredentialStatus.ProviderNotApplicable)); } if (_accountManager == null) { // we know this is a VSO endpoint but we are unable to get the credentials so we should // throw so that the other providers will not be called throw new InvalidOperationException(Resources.AccountProvider_FailedToLoadAccountManager); } var provider = (VSAccountProvider)await _accountManager .GetAccountProviderAsync(VSAccountProvider.AccountProviderIdentifier); if (provider == null) { // we know this is a VSO endpoint but we are unable to get the credentials so we should // throw so that the other providers will not be called throw new InvalidOperationException(Resources.AccountProvider_FailedToLoadVSOAccountProvider); } // Ask keychain for all accounts var accounts = _accountManager.Store.GetAllAccounts(); // Look through the accounts to see what ones have the VSO tenant in them (collected from // the LookupTenant() call at the top of the method). foreach (var account in accounts) { var tenant = _loginProvider.FindTenantInAccount(account, uriTenantId, provider); if (tenant != null) { posibleAccounts.Add(new AccountAndTenant(account, tenant)); } } ICredentials credentials; if (posibleAccounts.Count == 1) { // If we only have one posible account use it credentials = await _loginProvider.GetTokenFromAccount( posibleAccounts[0], provider, nonInteractive, cancellationToken); if (credentials == null) { throw new InvalidOperationException(Resources.AccountProvider_NoValidCrededentialsFound); } if (isRetry) { var hasAccess = await _loginProvider.AccountHasAccess( uri, proxy, credentials, cancellationToken); if (!hasAccess) { // The account didn't have access and we are on a retry so the token didn't expire. // we either need to prompt the user for different creds or fail in this case credentials = await _loginProvider.PromptUserForAccount( uriTenantId, provider, nonInteractive, cancellationToken); } } } else if (posibleAccounts.Count > 1) { var accountsWithAccess = new List <ICredentials>(); foreach (var account in posibleAccounts) { ICredentials cred = null; cred = await _loginProvider.GetTokenFromAccount( account, provider, nonInteractive : true, cancellationToken : cancellationToken); if (cred == null) { continue; } var hasAccess = await _loginProvider.AccountHasAccess(uri, proxy, cred, cancellationToken); if (hasAccess) { accountsWithAccess.Add(cred); } } if (accountsWithAccess.Count == 1) { credentials = accountsWithAccess[0]; } else { // we couldn't finde a unique account with access to the endpoint so we are going to have // to ask the user... credentials = await _loginProvider.PromptUserForAccount( uriTenantId, provider, nonInteractive, cancellationToken); } } else // count == 0 so we should prompt the user { credentials = await _loginProvider.PromptUserForAccount( uriTenantId, provider, nonInteractive, cancellationToken); } if (credentials == null) { // No credentials found but we know that this is a VSO endpoint so we want to throw an // exception to prevent the other providers from being called throw new InvalidOperationException(Resources.AccountProvider_NoValidCrededentialsFound); } var response = new CredentialResponse(credentials); return(response); }
private void AddToCredentialCache(Uri uri, CredentialRequestType type, ICredentialProvider provider, CredentialResponse credentials) { _providerCredentialCache[CredentialsKeyHelper.GetCacheKey(uri, type, provider)] = credentials; }
public bool IsValidResponse(CredentialResponse response) { return(response is not null && Enum.IsDefined(typeof(CredentialStatus), response.Status)); }
public CredentialResponse GetCredentials(CredentialRequest credentialRequest) { if (credentialRequest == null) { log.ErrorFormat("{0}{1}", "CredentialService-GetCredentials", "CredentialRequest is null!"); return(new CredentialResponse { HasError = true, ErrorDetail = "CredentialRequest is null!" }); } else if (string.IsNullOrEmpty(credentialRequest.UserCode)) { log.ErrorFormat("{0}{1}", "CredentialService-GetCredentials", "UserCode is empty!"); return(new CredentialResponse { HasError = true, ErrorDetail = "UserCode is empty!" }); } else { try { DateTime dateTimeStart = DateTime.Now; MenuResponse result = menuService.GetMenus().Result; //menuCacheService.GetCachedMenu(credentialRequest.UserCode); log.InfoFormat("{0}-{1}", "GetCachedMenuTimer", (DateTime.Now - dateTimeStart).TotalMilliseconds); if (result == null) { log.ErrorFormat("CredentialService-GetCredentials GetCachedMenu result is null Menu bilgilerine ulaşılamadı!"); return(new CredentialResponse { HasError = true, ErrorDetail = "Menu bilgilerine ulaşılamadı!" }); } else if (result.Applications == null) { log.ErrorFormat("CredentialService-GetCredentials Applications is null Uygulama bilgilerine ulaşılamadı!"); return(new CredentialResponse { HasError = true, ErrorDetail = "Uygulama bilgilerine ulaşılamadı!" }); } else { var applications = JsonConvert.DeserializeObject(result.Applications); ImsCredentialRequest imsCredentialRequest = new ImsCredentialRequest { Applications = applications, UserCode = credentialRequest.UserCode }; User user = userAuthorityService.GetUserCredentials(imsCredentialRequest); if (user == null) { log.ErrorFormat("{0}{1}{2}", "CredentialService-GetCredentials", "Applications : " + result.Applications, "UserCode: " + credentialRequest.UserCode); return(new CredentialResponse { HasError = true, ErrorDetail = "Kullanıcı bilgileri SSO uygulamasından alınamadı!" }); } else { CredentialResponse credentialResponse = new CredentialResponse { MenuTree = GetMenuTree(user, result), ApplicationCredentials = GetApplicationCredentials(user), Applications = GetApplicationsMultiLanguageValues(applications, user), DysUrl = TryGetUrl(Constants.DysUrl), DashBoardApiUrl = TryGetUrl(Constants.DashBoardApiUrl), IsProduction = GetEnvironmentInfo(), ProductionControlFlag = GetProductionControlFlag(), IsTablet = false, //TabletDetectorHelper.IsTabletModeEnabled(HttpContext.Current.Request), ChannelDate = GetChannelDate(credentialRequest.ChannelCode) }; return(credentialResponse); } } } catch (Exception ex) { log.ErrorFormat("CredentialService Error : {0}-{1}", ex, "CredentialService-GetCredentials"); return(new CredentialResponse { HasError = true, ErrorDetail = string.Format("{0} Message: {1} InnerException: {2} StackTrace: {3}", "Kullanıcı yetkileri alınamadı: Detay:", ex.Message, ex.InnerException, ex.StackTrace) }); } } }