/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param> /// <param name="parameters">An object of type PlatformParameters which may pass additional parameters used for authorization.</param> /// <returns>It contains Access Token, its expiration time, user information.</returns> public async Task <AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, IPlatformParameters parameters) { return(await this .AcquireTokenCommonAsync(resource, clientId, redirectUri, parameters, UserIdentifier.AnyUser) .ConfigureAwait(false)); }
public static async Task Search(object sender, RoutedEventArgs e, GridView SearchResults, TextBox SearchTermText, TextBlock StatusResult, IPlatformParameters parent) { if (string.IsNullOrEmpty(SearchTermText.Text)) { MessageDialog dialog = new MessageDialog("Please enter a valid search term."); await dialog.ShowAsync(); return; } List<User> results = await DirectorySearcherLib.DirectorySearcher.SearchByAlias(SearchTermText.Text, parent); if (results.Count == 0) { StatusResult.Text = "User Not Found. Try Another Term."; StatusResult.Foreground = new SolidColorBrush(Windows.UI.Colors.White); results.Add(new User()); } else if (results[0].error != null) { StatusResult.Text = "Error! " + results[0].error; StatusResult.Foreground = new SolidColorBrush(Windows.UI.Colors.Red); } else { StatusResult.Text = "Success"; StatusResult.Foreground = new SolidColorBrush(Windows.UI.Colors.Green); } SearchResults.ItemsSource = results; }
public override void AddPromptBehaviorQueryParameter(IPlatformParameters parameters, DictionaryRequestParameters authorizationRequestParameters) { PlatformParameters authorizationParameters = (parameters as PlatformParameters); if (authorizationParameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } PromptBehavior promptBehavior = authorizationParameters.PromptBehavior; // ADFS currently ignores the parameter for now. switch (promptBehavior) { case PromptBehavior.Always: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login; break; case PromptBehavior.RefreshSession: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession; break; case PromptBehavior.Never: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.AttemptNone; break; } }
/// <summary>Creates an Azure Active Directory token provider.</summary> /// <param name="authContext">AuthenticationContext for AAD.</param> /// <param name="clientId">ClientId for AAD.</param> /// <param name="redirectUri">The redirectUri on Client App.</param> /// <param name="platformParameters">Platform parameters</param> /// <param name="userIdentifier">User Identifier</param> /// <returns>The <see cref="TokenProvider" /> for returning Json web token.</returns> internal static TokenProvider CreateAadTokenProvider( AuthenticationContext authContext, string clientId, Uri redirectUri, IPlatformParameters platformParameters, UserIdentifier userIdentifier = null) { if (authContext == null) { throw new ArgumentNullException(nameof(authContext)); } if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (redirectUri == null) { throw new ArgumentNullException(nameof(redirectUri)); } if (platformParameters == null) { throw new ArgumentNullException(nameof(platformParameters)); } return(new AzureActiveDirectoryTokenProvider(authContext, clientId, redirectUri, platformParameters, userIdentifier)); }
public override void AddPromptBehaviorQueryParameter(IPlatformParameters parameters, DictionaryRequestParameters authorizationRequestParameters) { PlatformParameters authorizationParameters = (parameters as PlatformParameters); if (authorizationParameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } PromptBehavior promptBehavior = authorizationParameters.PromptBehavior; switch (promptBehavior) { case PromptBehavior.Always: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login; break; case PromptBehavior.SelectAccount: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.SelectAccount; break; case PromptBehavior.RefreshSession: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession; break; } }
public static async Task <string> GetData(IPlatformParameters platformParameters) { AuthenticationContext authContext = new AuthenticationContext(authority); AuthenticationResult result = null; string data = string.Empty; try { result = await authContext.AcquireTokenAsync(resourceId, clientId, redirectURI, platformParameters); using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await httpClient.GetAsync(baseAddress + "?name=mohit"); if (response.IsSuccessStatusCode) { return(response.Content.ReadAsStringAsync().Result); } return("Failed"); } } catch (Exception ex) { return(string.Empty); } }
public SilentRequest(AuthenticationRequestParameters authenticationRequestParameters, string userIdentifer, IPlatformParameters parameters, bool forceRefresh) : this(authenticationRequestParameters, (User)null, parameters, forceRefresh) { this.User = this.MapIdentifierToUser(userIdentifer); PlatformPlugin.BrokerHelper.PlatformParameters = parameters; this.SupportADFS = false; }
public IWebUI CreateAuthenticationDialog(IPlatformParameters inputParameters) { this.parameters = inputParameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } switch (this.parameters.PromptBehavior) { case PromptBehavior.Auto: return(new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }); case PromptBehavior.Always: case PromptBehavior.RefreshSession: return(new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }); case PromptBehavior.Never: return(new SilentWebUI { OwnerWindow = this.parameters.OwnerWindow }); default: throw new InvalidOperationException("Unexpected PromptBehavior value"); } }
private static IPlatformParameters GetPlatformParametersInstance(string promptBehaviorString) { IPlatformParameters platformParameters = null; PromptBehavior pb = PromptBehavior.Auto; if (!string.IsNullOrEmpty(promptBehaviorString)) { pb = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), promptBehaviorString, true); } #if __ANDROID__ platformParameters = new PlatformParameters(this); #else #if __IOS__ platformParameters = new PlatformParameters(this); #else #if (WINDOWS_UWP || WINDOWS_APP) platformParameters = new PlatformParameters(PromptBehavior.Always, false); #else //desktop platformParameters = new PlatformParameters(pb, null); #endif #endif #endif return(platformParameters); }
public WebUI(IPlatformParameters parameters) { this.parameters = parameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } }
public WebUI(IPlatformParameters parameters) { this.parameters = parameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } }
/// <summary> /// Check when there are multiple users in the cache with the same /// authority, clientId, resource but different unique and displayId's that /// we can correctly get them from the cache without a multiple token /// detected exception. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static async Task TestUniqueIdDisplayableIdLookup(IPlatformParameters parameters) { string authority = "https://www.gotJwt.com/"; string clientId = Guid.NewGuid().ToString(); string resource = Guid.NewGuid().ToString(); string tenantId = Guid.NewGuid().ToString(); string uniqueId = Guid.NewGuid().ToString(); string displayableId = Guid.NewGuid().ToString(); Uri redirectUri = new Uri("https://www.GetJwt.com"); var authenticationResult = CreateCacheValue(uniqueId, displayableId); authority = authority + tenantId + "/"; UserCredential credential = new UserCredential(displayableId); AuthenticationContext tempContext = new AuthenticationContext(authority, false); var localCache = tempContext.TokenCache; localCache.Clear(); // Add first user into cache resource = Guid.NewGuid().ToString(); clientId = Guid.NewGuid().ToString(); uniqueId = Guid.NewGuid().ToString(); displayableId = Guid.NewGuid().ToString(); var cacheValue = CreateCacheValue(uniqueId, displayableId); AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId), cacheValue); //Add second user into cache uniqueId = Guid.NewGuid().ToString(); displayableId = Guid.NewGuid().ToString(); cacheValue = CreateCacheValue(uniqueId, displayableId); AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId), cacheValue); var acWithLocalCache = new AuthenticationContext(authority, false, localCache); var userId = new UserIdentifier(uniqueId, UserIdentifierType.UniqueId); var userIdUpper = new UserIdentifier(displayableId.ToUpper(), UserIdentifierType.RequiredDisplayableId); var authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, parameters, userId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, parameters, userIdUpper); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userIdUpper); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); }
internal AzureActiveDirectoryTokenProvider(AuthenticationContext authContext, string clientId, Uri redirectUri, IPlatformParameters platformParameters, UserIdentifier userIdentifier) { this.authContext = authContext; this.clientId = clientId; this.redirectUri = redirectUri; this.platformParameters = platformParameters; this.userIdentifier = userIdentifier; this.authType = AuthType.InteractiveUserLogin; }
/// <summary> /// Acquires an access token from the authority on behalf of a user, passing in the necessary claims for authentication. It requires using a user token previously received. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param> /// <param name="parameters">Instance of PlatformParameters containing platform specific arguments and information.</param> /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param> /// <param name="extraQueryParameters">This parameter will be appended as is to the query string in the HTTP authentication request to the authority. The parameter can be null.</param> /// <param name="claims">Additional claims that are needed for authentication. Acquired from the AdalClaimChallengeException</param> /// <returns>It contains Access Token and the Access Token's expiration time.</returns> public async Task <AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, string claims) { return(await this.AcquireTokenWithClaimsCommonAsync(resource, new ClientKey(clientId), redirectUri, parameters, userId, extraQueryParameters, this.CreateWebAuthenticationDialog(parameters), claims) .ConfigureAwait(false)); }
public WebUI(IPlatformParameters parameters) { if (!(parameters is PlatformParameters)) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } this.useCorporateNetwork = ((PlatformParameters)parameters).UseCorporateNetwork; }
public WebUI(IPlatformParameters parameters) { if (!(parameters is PlatformParameters)) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } this.useCorporateNetwork = ((PlatformParameters)parameters).UseCorporateNetwork; }
public AddAMSAccount2Browse(TokenCredentials credentials, List <Subscription> subscriptions, AzureEnvironment environment, List <TenantIdDescription> myTenants, IPlatformParameters parameters) { InitializeComponent(); Icon = Bitmaps.Azure_Explorer_ico; this.credentials = credentials; this.subscriptions = subscriptions; this.environment = environment; _myTenants = myTenants; _parameters = parameters; }
public IOSAppUtilities(IPlatformParameters parameters, ITelemetry telemetry = null) { this.parameters = parameters; AppResources.Culture = DependencyService.Get <ILocalize>().GetCurrentCultureInfo(); DependencyService.Get <ILocalize>().SetLocale(); InitializeAppPackage(new IOSAppPackage()); InitializeTelemetry(telemetry); }
public static async Task Authenticate(IPlatformParameters parameters) { string clientId = "0583a69c-0da8-446d-9bd4-a4b06a72cd40"; Uri returnUri = new Uri("https://crm.infragistics.com/InfragisticsInc/main.aspx"); var infragisticsAuthority = "https://login.windows.net/5467154b-1b75-4824-9369-916e4fb500db/oauth2/token"; var _authenticationContext = new AuthenticationContext(infragisticsAuthority, false); AuthResult = await _authenticationContext.AcquireTokenAsync(clientId, clientId, returnUri, parameters); }
public WebUI(IPlatformParameters parameters) { this.parameters = parameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } this.didEnterBackgroundNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.DidEnterBackgroundNotification, OnMoveToBackground); this.willEnterForegroundNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, OnMoveToForeground); }
private async Task <IResponse <AuthenticationResult> > AuthenticateAsync(IPlatformParameters promptBehavior) { try { if (_authenticationResult == null || _authenticationResult.ExpiresOn >= DateTime.Now) { if (_tokenCache == null) { var cacheFolder = Path.GetFullPath( Path.GetDirectoryName( Assembly.GetEntryAssembly().Location)); _tokenCache = new FilesBasedTokenCache( Path.Combine(cacheFolder, _adalV3CacheFileName), Path.Combine(cacheFolder, _msalCacheFileName)); } if (_context == null) { _context = new AuthenticationContext("https://login.windows.net/common", _tokenCache); if (_context.TokenCache.Count > 0) { var homeTenant = _context.TokenCache.ReadItems().First().TenantId; _context = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant, _tokenCache); } } AuthenticationResult result = null; try { result = await _context.AcquireTokenSilentAsync(_azureDevOpsResourceId, _clientId); } catch (AdalException adalException) { if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently || adalException.ErrorCode == AdalError.InteractionRequired) { result = await _context.AcquireTokenAsync(_azureDevOpsResourceId, _clientId, new Uri(_replyUri), promptBehavior); } } if (result == null || string.IsNullOrEmpty(result.AccessToken)) { return(Response <AuthenticationResult> .FromFailure("Unable to acquire access token")); } _authenticationResult = result; } return(Response <AuthenticationResult> .FromSuccess(_authenticationResult)); } catch (Exception ex) { return(Response <AuthenticationResult> .FromException("There was an error acquiring an access token", ex)); } }
public static async Task SignInAsync(IPlatformParameters context) { authenticationParentUiContext = context; if (AppSettings.OutlookIntegration) { await GetGraphClientAsync (); return; } await SignInAsync (); }
public SilentRequest(AuthenticationRequestParameters authenticationRequestParameters, User user, IPlatformParameters parameters, bool forceRefresh) : base(authenticationRequestParameters) { if (user != null) { this.User = user; } PlatformPlugin.BrokerHelper.PlatformParameters = parameters; this.SupportADFS = false; this.ForceRefresh = forceRefresh; }
public AcquireTokenSilentHandler(HandlerData handlerData, User user, IPlatformParameters parameters, bool forceRefresh) : base(handlerData) { if (user != null) { this.User = user; } PlatformPlugin.BrokerHelper.PlatformParameters = parameters; this.SupportADFS = false; this.ForceRefresh = forceRefresh; }
public IWebUI CreateAuthenticationDialog(IPlatformParameters inputParameters) { this.parameters = inputParameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } return(new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }); }
public static async Task SignInAsync(IPlatformParameters context) { authenticationParentUiContext = context; if (AppSettings.OutlookIntegration) { await GetGraphClientAsync(); } else { await SignInAsync(); } }
public async Task<string> GetTokenInteractiveWithMsAppAsync(IPlatformParameters parameters) { try { var result = await context.AcquireTokenAsync(sts.ValidResource, sts.ValidClientId, null, parameters, new UserIdentifier(sts.ValidUserName, UserIdentifierType.OptionalDisplayableId)); return result.AccessToken; } catch (Exception ex) { return ex.Message; } }
/// <summary> /// Create a JwtHttpHandler. Use services.AddHttpHandler to add one and <see cref="ConfigurePrimaryHttpMessageHandler"/> if you need to /// customize the HttpHandler. /// </summary> /// <param name="settings">The settings needed for the <see cref="ITokenProvider"/>.</param> /// <param name="handler">The handler, can be a <see cref="DelegatingHandler"/></param> public JwtHttpHandler(IContainerResolve container, IKeyValueSettings settings, IPlatformParameters parameters = null) { _container = container ?? throw new ArgumentNullException(nameof(container)); _logger = container.Resolve <ILogger <JwtHttpHandler> >(); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _parameters = parameters; _settingsName = null; container.TryResolve <IApplicationContext>(out _applicationContext); }
public WebUI(IPlatformParameters parameters) { this.parameters = parameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } if (this.parameters.CallerActivity == null) { throw new ArgumentException("CallerActivity should be set in PlatformParameters", "CallerActivity"); } }
public static void InjectDependecies(IWebUIFactory webUIFactory, ITokenCachePlugin tokenCachePlugin, LoggerBase logger, PlatformInformationBase platformInformation, ICryptographyHelper cryptographyHelper, IDeviceAuthHelper deviceAuthHelper, IBrokerHelper brokerHelper, IPlatformParameters platformParameters) { WebUIFactory = webUIFactory; TokenCachePlugin = tokenCachePlugin; Logger = logger; PlatformInformation = platformInformation; CryptographyHelper = cryptographyHelper; DeviceAuthHelper = deviceAuthHelper; BrokerHelper = brokerHelper; DefaultPlatformParameters = platformParameters; }
internal IWebUI CreateWebAuthenticationDialog(IPlatformParameters parameters) { IWebUIFactory2 factory2 = PlatformPlugin.WebUIFactory as IWebUIFactory2; if (factory2 != null) { return(factory2.CreateAuthenticationDialog2(parameters, this.additionalAuthenticationDialogContext)); } else { return(PlatformPlugin.WebUIFactory.CreateAuthenticationDialog(parameters)); } }
public override bool GetCacheLoadPolicy(IPlatformParameters parameters) { PlatformParameters authorizationParameters = (parameters as PlatformParameters); if (authorizationParameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } PromptBehavior promptBehavior = authorizationParameters.PromptBehavior; return(promptBehavior != PromptBehavior.Always && promptBehavior != PromptBehavior.RefreshSession); }
public override AuthenticationRequestParameters CreateRequestParameters(Authority authority, string[] scope, string policy, User user, TokenCache cache) { AuthenticationRequestParameters parameters = base.CreateRequestParameters(authority, scope, policy, user, cache); parameters.ClientKey = new ClientKey(this.ClientId); if (this.PlatformParameters == null) { this.PlatformParameters = PlatformPlugin.DefaultPlatformParameters; } return(parameters); }
public static void InjectDependecies(IWebUIFactory webUIFactory, ITokenCachePlugin tokenCachePlugin, LoggerBase logger, PlatformInformationBase platformInformation, ICryptographyHelper cryptographyHelper, IDeviceAuthHelper deviceAuthHelper, IBrokerHelper brokerHelper, IPlatformParameters platformParameters) { WebUIFactory = webUIFactory; TokenCachePlugin = tokenCachePlugin; Logger = logger; PlatformInformation = platformInformation; CryptographyHelper = cryptographyHelper; DeviceAuthHelper = deviceAuthHelper; BrokerHelper = brokerHelper; DefaultPlatformParameters = platformParameters; }
public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, IWebUI webUI) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User) { this.redirectUri = PlatformPlugin.PlatformInformation.ValidateRedirectUri(redirectUri, this.CallState); if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment)) { throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } this.authorizationParameters = parameters; this.redirectUriRequestParameter = PlatformPlugin.PlatformInformation.GetRedirectUriAsString(this.redirectUri, this.CallState); if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.userId = userId; if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this.extraQueryParameters = extraQueryParameters; this.webUi = webUI; this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.LoadFromCache = (tokenCache != null && parameters != null && PlatformPlugin.PlatformInformation.GetCacheLoadPolicy(parameters)); this.SupportADFS = true; this.CacheQueryData.DisplayableId = this.DisplayableId; this.CacheQueryData.UniqueId = this.UniqueId; this.brokerParameters["force"] = "NO"; if (userId != UserIdentifier.AnyUser) { this.brokerParameters["username"] = userId.Id; } else { this.brokerParameters["username"] = string.Empty; } this.brokerParameters["username_type"] = userId.Type.ToString(); this.brokerParameters["redirect_uri"] = redirectUri.AbsoluteUri; this.brokerParameters["extra_qp"] = extraQueryParameters; PlatformPlugin.BrokerHelper.PlatformParameters = authorizationParameters; }
public async Task <string> GetTokenInteractiveWithMsAppAsync(IPlatformParameters parameters) { try { context = new AuthenticationContext(Sts.Authority, true); var result = await context.AcquireTokenAsync(Sts.ValidResource, Sts.ValidClientId, null, parameters, new UserIdentifier(Sts.ValidUserName, UserIdentifierType.OptionalDisplayableId)); return(result.AccessToken); } catch (Exception ex) { return(ex.Message); } }
/// <summary>Creates an Azure Active Directory token provider.</summary> /// <param name="authContext">AuthenticationContext for AAD.</param> /// <param name="clientId">ClientId for AAD.</param> /// <param name="redirectUri">The redirectUri on Client App.</param> /// <param name="platformParameters">Platform parameters</param> /// <param name="userIdentifier">User Identifier</param> /// <returns>The <see cref="TokenProvider" /> for returning Json web token.</returns> public static TokenProvider CreateAadTokenProvider( AuthenticationContext authContext, string clientId, Uri redirectUri, IPlatformParameters platformParameters, UserIdentifier userIdentifier = null) { Guard.ArgumentNotNull(nameof(authContext), authContext); Guard.ArgumentNotNullOrWhiteSpace(nameof(clientId), clientId); Guard.ArgumentNotNull(nameof(redirectUri), redirectUri); Guard.ArgumentNotNull(nameof(platformParameters), platformParameters); return(new AzureActiveDirectoryTokenProvider(authContext, clientId, redirectUri, platformParameters, userIdentifier)); }
public async Task <string> GetTokenSilentAsync(IPlatformParameters parameters) { try { AuthenticationContext context = new AuthenticationContext(Sts.Authority, true); var result = await context.AcquireTokenSilentAsync(Sts.ValidResource, Sts.ValidClientId, GetUserIdentifier(), parameters); return(result.AccessToken); } catch (Exception ex) { return(GetErrorMessage(ex)); } }
public async Task SignInAsync(IPlatformParameters context) { await MicrosoftGraphService.SignInAsync(context); var currentPatient = await GetPatientInfoAsync(); if (currentPatient != null) { AppSettings.CurrentPatientId = currentPatient.PatientId; // We first get patient's picture from backend MicrosoftGraphService.LoggedUserPhoto = currentPatient.Picture; // And, then, try to get a newer one from Microsoft Graph MicrosoftGraphService.LoggedUserPhoto = await MicrosoftGraphService.GetUserPhotoAsync(); } _messenger.Publish(new LoggedUserInfoChangedMessage(this)); }
public async Task<string> GetTokenSilentAsync(IPlatformParameters parameters) { try { app = new PublicClientApplication("https://login.windows.net/common", "CLIENT_ID"); var result = await app.AcquireTokenSilentAsync(Sts.ValidScope, Sts.ValidUserName); return result.Token; } catch (Exception ex) { string msg = ex.Message + "\n" + ex.StackTrace; return msg; } }
public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string[] scope, string[] additionalScope, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, IWebUI webUI) : base(authenticator, tokenCache, scope, new ClientKey(clientId), TokenSubjectType.User) { this.redirectUri = PlatformPlugin.PlatformInformation.ValidateRedirectUri(redirectUri, this.CallState); if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment)) { throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } this.authorizationParameters = parameters; if (!ADALScopeHelper.IsNullOrEmpty(additionalScope)) { this.additionalScope = additionalScope; } else { this.additionalScope = new string[] {}; } ValidateScopeInput(scope.Union(this.additionalScope).ToArray()); this.redirectUriRequestParameter = PlatformPlugin.PlatformInformation.GetRedirectUriAsString(this.redirectUri, this.CallState); if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.userId = userId; if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this.extraQueryParameters = extraQueryParameters; this.webUi = webUI; this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.LoadFromCache = (tokenCache != null && parameters != null && PlatformPlugin.PlatformInformation.GetCacheLoadPolicy(parameters)); this.SupportADFS = false; }
public InteractiveRequest(AuthenticationRequestParameters authenticationRequestParameters, string[] additionalScope, Uri redirectUri, IPlatformParameters parameters, string loginHint, UiOptions? uiOptions, string extraQueryParameters, IWebUI webUI) : base(authenticationRequestParameters) { this._redirectUri = PlatformPlugin.PlatformInformation.ValidateRedirectUri(redirectUri, this.CallState); if (!string.IsNullOrWhiteSpace(this._redirectUri.Fragment)) { throw new ArgumentException(MsalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } _additionalScope = new HashSet<string>(); if (!MsalStringHelper.IsNullOrEmpty(additionalScope)) { this._additionalScope = additionalScope.CreateSetFromArray(); } ValidateScopeInput(this._additionalScope); this._authorizationParameters = parameters; this._redirectUriRequestParameter = PlatformPlugin.PlatformInformation.GetRedirectUriAsString(this._redirectUri, this.CallState); this._loginHint = loginHint; if (!string.IsNullOrWhiteSpace(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this._extraQueryParameters = extraQueryParameters; this._webUi = webUI; this._uiOptions = uiOptions; this.LoadFromCache = false; //no cache lookup and refresh for interactive. this.SupportADFS = false; if (string.IsNullOrWhiteSpace(loginHint) && _uiOptions == UiOptions.ActAsCurrentUser) { throw new ArgumentException(MsalErrorMessage.LoginHintNullForUiOption, "loginHint"); } PlatformPlugin.BrokerHelper.PlatformParameters = _authorizationParameters; }
public IWebUI CreateAuthenticationDialog(IPlatformParameters inputParameters) { this.parameters = inputParameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } switch (this.parameters.PromptBehavior) { case PromptBehavior.Auto: return new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }; case PromptBehavior.Always: case PromptBehavior.RefreshSession: return new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }; case PromptBehavior.Never: return new SilentWebUI { OwnerWindow = this.parameters.OwnerWindow }; default: throw new InvalidOperationException("Unexpected PromptBehavior value"); } }
public static async Task TokenCacheKeyTestAsync(IPlatformParameters parameters) { CheckPublicGetSets(); string authority = "https://www.gotJwt.com/"; string clientId = Guid.NewGuid().ToString(); string resource = Guid.NewGuid().ToString(); string tenantId = Guid.NewGuid().ToString(); string uniqueId = Guid.NewGuid().ToString(); string displayableId = Guid.NewGuid().ToString(); Uri redirectUri = new Uri("https://www.GetJwt.com"); var authenticationResult = CreateCacheValue(uniqueId, displayableId); authority = authority + tenantId + "/"; UserCredential credential = new UserCredential(displayableId); AuthenticationContext tempContext = new AuthenticationContext(authority, false); var localCache = tempContext.TokenCache; localCache.Clear(); // @Resource, Credential TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId); AddToDictionary(localCache, tokenCacheKey, authenticationResult); AuthenticationContext acWithLocalCache = new AuthenticationContext(authority, false, localCache); AuthenticationResult authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, credential); AreAuthenticationResultsEqual(authenticationResult.Result, authenticationResultFromCache); // Duplicate throws error authenticationResult.Result.UserInfo.UniqueId = null; AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, displayableId), authenticationResult); try { await acWithLocalCache.AcquireTokenAsync(resource, clientId, credential); Verify.Fail("Exception expected"); } catch (AdalException adae) { Verify.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements")); } try { AuthenticationContext acWithDefaultCache = new AuthenticationContext(authority, false); await acWithDefaultCache.AcquireTokenAsync(resource, clientId, credential); Verify.Fail("Exception expected"); } catch (AdalException adae) { Verify.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements")); } // @resource && @clientId acWithLocalCache = new AuthenticationContext(authority, false, localCache); localCache.Clear(); var cacheValue = CreateCacheValue(uniqueId, displayableId); resource = Guid.NewGuid().ToString(); clientId = Guid.NewGuid().ToString(); TokenCacheKey tempKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, null); AddToDictionary(localCache, tempKey, cacheValue); RemoveFromDictionary(localCache, tempKey); Verify.IsFalse(localCache.tokenCacheDictionary.ContainsKey(tempKey)); AddToDictionary(localCache, tempKey, cacheValue); authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, parameters); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); // @resource && @clientId && userId acWithLocalCache = new AuthenticationContext(authority, false, localCache); localCache.Clear(); resource = Guid.NewGuid().ToString(); clientId = Guid.NewGuid().ToString(); uniqueId = Guid.NewGuid().ToString(); displayableId = Guid.NewGuid().ToString(); cacheValue = CreateCacheValue(uniqueId, displayableId); AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId), cacheValue); var userId = new UserIdentifier(uniqueId, UserIdentifierType.UniqueId); var userIdUpper = new UserIdentifier(displayableId.ToUpper(), UserIdentifierType.RequiredDisplayableId); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userIdUpper); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); }
public ReplayerWebUI(IPlatformParameters parameters) { }
public InteractiveRequest(AuthenticationRequestParameters authenticationRequestParameters, string[] additionalScope, Uri redirectUri, IPlatformParameters parameters, User user, UiOptions uiOptions, string extraQueryParameters, IWebUI webUI) :this(authenticationRequestParameters, additionalScope, redirectUri, parameters, user?.DisplayableId, uiOptions, extraQueryParameters, webUI) { this.User = user; }
internal async Task<AuthenticationResult> AcquireTokenSilentCommonAsync(Authenticator authenticator, string[] scope, User user, IPlatformParameters parameters, string policy, bool forceRefresh) { if (parameters == null) { parameters = PlatformPlugin.DefaultPlatformParameters; } var handler = new SilentRequest(this.GetHandlerData(authenticator, scope, policy, this.UserTokenCache), user, parameters, forceRefresh); return await handler.RunAsync().ConfigureAwait(false); }
public string GetTokenInteractiveWithMsAppAsync(IPlatformParameters parameters) { try { /* app = new AuthenticationContext(Sts.Authority, true); var result = await app.AcquireTokenAsync(Sts.ValidScope, Sts.ValidClientId, null, parameters, new UserIdentifier(Sts.ValidUserName, UserIdentifierType.OptionalDisplayableId)); return result.Token;*/ return null; } catch (Exception ex) { return ex.Message; } }
public IWebUI CreateAuthenticationDialog(IPlatformParameters parameters) { return new WebUI(parameters); }
public AuthenticationHelperMSAL(IPlatformParameters platformParameters) { _identityClient = new PublicClientApplication(ClientId); _identityClient.PlatformParameters = platformParameters; }
public static void SetAuthenticationUiContext(IPlatformParameters UiContext) { authenticationParentUiContext = UiContext; }
public RecorderWebUI(IPlatformParameters parameters) { this.internalWebUI = (new WebUIFactory()).CreateAuthenticationDialog(parameters); }
public static async Task<List<User>> SearchByAlias(string alias, IPlatformParameters parent) // add this param { AuthenticationResult authResult = null; JObject jResult = null; List<User> results = new List<User>(); try { // To avoid the user consent page, input the values for your registered application above, // comment out the if statement immediately below, and replace the commonAuthority parameter // with https://login.windows.net/<your.tenant.domain.com> AuthenticationContext authContext = new AuthenticationContext(commonAuthority); if (authContext.TokenCache.ReadItems().Count() > 0) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, parent); } catch (Exception ee) { results.Add(new User { error = ee.Message }); return results; } try { string graphRequest = String.Format(CultureInfo.InvariantCulture, "{0}/{1}/users?api-version={2}&$filter=mailNickname eq '{3}'", graphResourceUri, authResult.TenantId, graphApiVersion, alias); //string graphRequest = String.Format(CultureInfo.InvariantCulture, "{0}/{1}/users?api-version={2}&$filter=startswith(mailNickname, '{3}')", graphResourceUri, authResult.TenantId, graphApiVersion, alias); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); HttpResponseMessage response = await client.SendAsync(request); string content = await response.Content.ReadAsStringAsync(); jResult = JObject.Parse(content); } catch (Exception ee) { results.Add(new User { error = ee.Message }); return results; } if (jResult["odata.error"] != null) { results.Add(new User { error = (string)jResult["odata.error"]["message"]["value"] }); return results; } if (jResult["value"] == null) { results.Add(new User { error = "Unknown Error." }); return results; } foreach (JObject result in jResult["value"]) { results.Add(new User { displayName = (string)result["displayName"], givenName = (string)result["givenName"], surname = (string)result["surname"], userPrincipalName = (string)result["userPrincipalName"], telephoneNumber = (string)result["telephoneNumber"] == null ? "Not Listed." : (string)result["telephoneNumber"] }); } return results; }
internal IWebUI CreateWebAuthenticationDialog(IPlatformParameters parameters) { return PlatformPlugin.WebUIFactory.CreateAuthenticationDialog(parameters); }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param> /// <param name="userId">Identifier of the user token is requested for. If created from DisplayableId, this parameter will be used to pre-populate the username field in the authentication form. Please note that the end user can still edit the username field and authenticate as a different user. /// If you want to be notified of such change with an exception, create UserIdentifier with type RequiredDisplayableId. This parameter can be <see cref="UserIdentifier"/>.Any.</param> /// <param name="parameters">Parameters needed for interactive flow requesting authorization code. Pass an instance of PlatformParameters.</param> /// <param name="extraQueryParameters">This parameter will be appended as is to the query string in the HTTP authentication request to the authority. The parameter can be null.</param> /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns> public async Task<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters) { return await this.AcquireTokenCommonAsync(resource, clientId, redirectUri, parameters, userId, extraQueryParameters); }
public void Initialize(IPlatformParameters parameters) { ActiveDirectoryB2CAuthenticationClient.PlatformParameters = parameters; }
public IWebUI CreateAuthenticationDialog(IPlatformParameters parameters) { throw new NotImplementedException(); }
private async Task<AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters = null) { var handler = new AcquireTokenInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, redirectUri, parameters, userId, extraQueryParameters, this.CreateWebAuthenticationDialog(parameters)); return await handler.RunAsync(); }
public IWebUI CreateAuthenticationDialog(IPlatformParameters inputParameters) { this.parameters = inputParameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } return new InteractiveWebUI { OwnerWindow = this.parameters.OwnerWindow }; }
public WebUI(IPlatformParameters parameters) { this.parameters = parameters as PlatformParameters; if (this.parameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } if (this.parameters.CallerActivity == null) { throw new ArgumentException("CallerActivity should be set in PlatformParameters", "CallerActivity"); } }