public static async Task<string> GetAccessToken() {
      if (string.IsNullOrEmpty(_accessToken)) {

        // fetch from stuff user claims
        var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

        // discover contact endpoint
        var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
        var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

        // create auth context
        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority,
          new EfAdalTokenCache(userObjectId));

        // authenticate
        var authResult =
          await
            authContext.AcquireTokenSilentAsync(
              string.Format("https://{0}.sharepoint.com", SettingsHelper.Office365TenantId), clientCredential,
              userIdentifier);

        // obtain access token
        _accessToken = authResult.AccessToken;
      }

      return _accessToken;
    }
        public static string GetAccessToken(string resource)
        {
            // get ClaimsPrincipal for current user
              ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;
              string signedInUserID = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value;
              string tenantID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
              string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

              ApplicationDbContext db = new ApplicationDbContext();
              ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID);

              string urlAuthorityRoot = ConfigurationManager.AppSettings["ida:AADInstance"];
              string urlAuthorityTenant = urlAuthorityRoot + tenantID;

              AuthenticationContext authenticationContext =
            new AuthenticationContext(urlAuthorityTenant, userTokenCache);

              Uri uriReplyUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

              string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
              string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
              ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

              UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId);

              AuthenticationResult authenticationResult =
            authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier).Result;

              return authenticationResult.AccessToken;
        }
    // GET: Discovery
    public async Task<ActionResult> Index()
    {
      // get instance of the authentication context using the token cache we created previously
      var signedInUser = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signedInUser));

      // create credentials for the application
      var appCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

      // get user identifier
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
      var userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create instance of DiscoveryClient
      var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () =>
        {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, appCred, userId);
          return authResult.AccessToken;
        });

      // query discovery service for endpoints
      var capabilitiesResults = await discoveryClient.DiscoverCapabilitiesAsync();

      return View(capabilitiesResults);
    }
    public static string GetAccessToken(string resource) {

      // get user ID in security cookie
      var signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

      // get token cache for signed in user
      ApplicationDbContext db = new ApplicationDbContext();      
      ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID);  
      AuthenticationContext authContext = new AuthenticationContext(Authority, userTokenCache);

      // Get credentials for user
      var clientCredential = new ClientCredential(clientId, clientSecret);

      // Create user identifier object using User ID for Azure Active Directory account
      string objectIdentifierID = "http://schemas.microsoft.com/identity/claims/objectidentifier";
      var userObjectId = ClaimsPrincipal.Current.FindFirst(objectIdentifierID).Value;
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // call to ADAL to get access token from cache of across network
      var authResult = authContext.AcquireTokenSilent(resource, clientCredential, userIdentifier);

      // obtain access token
      return authResult.AccessToken;

    }
        /// <summary>
        /// Create a token provider which can provide user tokens in the given context.  The user must have previously authenticated in the given context. 
        /// Tokens are retrieved from the token cache.
        /// </summary>
        /// <param name="context">The active directory authentication context to use for retrieving tokens.</param>
        /// <param name="clientId">The active directory client Id to match when retrieving tokens.</param>
        /// <param name="tokenAudience">The audience to match when retrieving tokens.</param>
        /// <param name="userId">The user id to match when retrieving tokens.</param>
        public UserTokenProvider(AuthenticationContext context, string clientId, Uri tokenAudience,
            UserIdentifier userId)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (string.IsNullOrWhiteSpace(clientId))
            {
                throw new ArgumentNullException("clientId");
            }
            if (tokenAudience == null)
            {
                throw new ArgumentNullException("tokenAudience");
            }
            if (userId == null)
            {
                throw new ArgumentNullException("userId");
            }

            this._authenticationContext = context;
            this._clientId = clientId;
            this._tokenAudience = tokenAudience.ToString();
            this._userid = userId;
        }
    public async Task<ActionResult> Open() {
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      string token = null;
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // get the activation parameters submitted from SharePoint
      ActivationParameters parameters = this.LoadActivationParameters();

      // get access token for unified api
      var authResult = await authContext.AcquireTokenSilentAsync(parameters.ResourceId, clientCredential, userIdentifier);
      token = authResult.AccessToken;

      // get contents of the file in SharePoint
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(parameters.FileGet);
      request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
      Stream responseStream = request.GetResponse().GetResponseStream();
      StreamReader srReader = new StreamReader(responseStream);
      var fileContents = srReader.ReadToEnd();

      // read XML feed
      XmlReader xmlReader = XmlReader.Create(fileContents);
      SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
      xmlReader.Close();

      ViewBag.FeedTitle = feed.Title.Text;
      ViewBag.Posts = feed.Items;
      return View();
    }
    private async Task<OutlookServicesClient> EnsureClientCreated() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover contact endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // create O365 discovery client 
      DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

          return authResult.AccessToken;
        });

      // query discovery service for endpoint for 'calendar' endpoint
      CapabilityDiscoveryResult dcr = await discovery.DiscoverCapabilityAsync("Contacts");

      // create an OutlookServicesclient
      return new OutlookServicesClient(dcr.ServiceEndpointUri,
        async () => {
          var authResult =
            await
              authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });
    }
    private async Task InitOneNoteRestConnection() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover onenote endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // authenticate with directory service
      var discoClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });

      // query discovery service for endpoint for onenote endpoint
      var discoCapabilityResult = await discoClient.DiscoverCapabilityAsync("Notes");

      // get details around onedrive endpoint (replace 1.0 with 2.0 for the new REST API)
      _oneNoteResourceId = discoCapabilityResult.ServiceResourceId;
      _oneNoteEndpoint = discoCapabilityResult.ServiceEndpointUri.ToString();
      var accessToken = (await authContext.AcquireTokenSilentAsync(_oneNoteResourceId, clientCredential, userIdentifier)).AccessToken;

      // set the access token on all requests for onenote API
      _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

      return;
    }
        public async static Task<AuthenticationResult> GetTokenAsync(AuthenticationContext ctx, string resourceId)
        {
            ClientCredential credential = new ClientCredential(OfficeSettings.ClientId, OfficeSettings.ClientSecret);
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            UserIdentifier ident = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            var redirectUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            try
            {
                var result = await ctx.AcquireTokenSilentAsync(resourceId, credential, ident);
                //var result = await ctx.AcquireTokenAsync(resourceId, credential);
                LastAuthority = ctx.Authority;
                return result;
            }
            catch (AdalException)
            {
                ctx.TokenCache.Clear();
                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public static AuthenticationResult RefreshTokenByAuthority(String authority)
 {
     var ctx = new AuthenticationContext(string.Format(Constants.loginAuthority + authority, Constants.tenant));
     // Refresh the token for the logged in user only.
     UserIdentifier userName = new UserIdentifier(Properties.Settings.Default["ADUserName"].ToString(), UserIdentifierType.OptionalDisplayableId);
     return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Auto, userName);
 }
        /// <summary>
        /// Authenticates the user silently using <see cref="AuthenticationContext.AcquireTokenSilentAsync(string, ClientAssertionCertificate, UserIdentifier)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientAssertionCertificate">The client assertion certificate of the application.</param>
        /// <param name="userIdentifier">The <see cref="UserIdentifier"/> of the user.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public async Task<IAuthenticationResult> AcquireTokenSilentAsync(
            string resource,
            ClientAssertionCertificate clientAssertionCertificate,
            UserIdentifier userIdentifier)
        {
            var result = await this.authenticationContext.AcquireTokenSilentAsync(resource, clientAssertionCertificate, userIdentifier);

            return result == null ? null : new AuthenticationResultWrapper(result);
        }
 public async static Task<string> AcquireAccessCodeAsync(AuthenticationContext context, string resource, string clientId, Uri redirectUri, UserIdentifier userId)
 {
     var handler = new AcquireTokenInteractiveHandler(context.Authenticator, context.TokenCache, resource, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto, null), userId, null,
         context.CreateWebAuthenticationDialog(new PlatformParameters(PromptBehavior.Auto, null)));
     handler.CallState = null;
     context.Authenticator.AuthorizationUri = context.Authority + "oauth2/authorize";
     await handler.AcquireAuthorizationAsync();
     return handler.authorizationResult.Code;
 }
 public Task<IAuthenticationResult> AcquireTokenAsync(
     string resource,
     string clientId,
     Uri redirectUri,
     PromptBehavior promptBehavior,
     UserIdentifier userIdentifier)
 {
     return Task.FromResult(this.AcquireTokenAsyncCallback(resource, clientId, redirectUri, userIdentifier));
 }
 public static string AcquireAccessCode(AuthenticationContext context, string resource, string clientId, Uri redirectUri, UserIdentifier userId)
 {
     var handler = new AcquireTokenInteractiveHandler(context.Authenticator, context.TokenCache, resource, clientId, redirectUri, PromptBehavior.Auto, userId, null,
         context.CreateWebAuthenticationDialog(PromptBehavior.Auto), true);
     handler.CallState = null;
     context.Authenticator.AuthorizationUri = context.Authority + "oauth2/authorize";
     handler.AcquireAuthorization();
     return handler.authorizationResult.Code;
 }
        public static async Task<string> GetAccessToken(string resource)
        {
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimsObjectIdentifier).Value;
            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
            var authContext = GetAuthContext();

            var authResult = await authContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier);
            return authResult.AccessToken;
        }
        /// <summary>
        /// Authenticates the user using <see cref="AuthenticationContext.AcquireTokenAsync(string, string, Uri, PromptBehavior, UserIdentifier)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientId">The client ID of the application.</param>
        /// <param name="redirectUri">The redirect URI of the application.</param>
        /// <param name="promptBehavior">The <see cref="PromptBehavior"/> for authentication.</param>
        /// <param name="userIdentifier">The <see cref="UserIdentifier"/> for authentication.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public async Task<IAuthenticationResult> AcquireTokenAsync(
            string resource,
            string clientId,
            Uri redirectUri,
            PromptBehavior promptBehavior,
            UserIdentifier userIdentifier)
        {
            var result = await this.authenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, promptBehavior, userIdentifier);

            return result == null ? null : new AuthenticationResultWrapper(result);
        }
        public static AuthenticationResult GetInteractiveLogin(String Username = null, String authority = "common")
        {
            var ctx = new AuthenticationContext(string.Format(Constants.loginAuthority + authority, Constants.tenant));

            if (!String.IsNullOrWhiteSpace(Username))
            {
                UserIdentifier user = new UserIdentifier(Username, UserIdentifierType.RequiredDisplayableId);
                return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Always, user);
            }
            else return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Always);
        }
        public static async Task<string> GetAccessTokenAsync(string resource)
        {
            var clientCredential = new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey);

            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            var context = GetAuthenticationContext();
            var token = await context.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier);
            return token.AccessToken;
        }
        private async Task<string> GetGraphAccessTokenAsync()
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureAdAuthority, new ADALTokenCache(signInUserId));
            var result = await authContext.AcquireTokenSilentAsync(SettingsHelper.AzureAdGraphResourceURL, clientCredential, userIdentifier);
            return result.AccessToken;
        }
 public static async Task<string> GetGraphAccessTokenAsync()
 {
     var AzureAdGraphResourceURL = "https://graph.microsoft.com/";
     var Authority = ConfigurationManager.AppSettings["ida:AADInstance"] + ConfigurationManager.AppSettings["ida:TenantId"];
     var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
     var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     var clientCredential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:ClientSecret"]);
     var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
     AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signInUserId));
     var result = await authContext.AcquireTokenSilentAsync(AzureAdGraphResourceURL, clientCredential, userIdentifier);
     return result.AccessToken;
 }
        public AcquireTokenSilentHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserIdentifier userId, bool callSync)
            : base(authenticator, tokenCache, resource, clientKey, clientKey.HasCredential ? TokenSubjectType.UserPlusClient : TokenSubjectType.User, callSync)
        {
            if (userId == null)
            {
                throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
            }

            this.UniqueId = userId.UniqueId;
            this.DisplayableId = userId.DisplayableId;
            this.UserIdentifierType = userId.Type;

            this.SupportADFS = true;
        }
Example #22
0
        public static AuthenticationResult getToken(string tenantId, string userName)
        {
            var authContext = new AuthenticationContext(String.Format("https://login.windows.net/{0}", tenantId));
            var user = new UserIdentifier(userName, UserIdentifierType.OptionalDisplayableId);
            // get a token for - using the powershell clientid (1950a258-227b-4e31-a9cf-717495945fc2)
            var result = authContext.AcquireToken("https://graph.windows.net/", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior.Auto, user);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain token");
            }

            return result;
        }
        public static async Task<DiscoveryClient> GetDiscoveryClient(string capability)
        {
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimsObjectIdentifier).Value;
            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
            var authContext = GetAuthContext();

            _DiscoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
                async () =>
                {
                    return await GetAccessToken(SettingsHelper.O365DiscoveryResourceId);
                });

            var dcr = await _DiscoveryClient.DiscoverCapabilityAsync(capability);

            return _DiscoveryClient;
        }
Example #24
0
        /// <summary>
        /// Gets a resource specific access token for Power BI ("https://analysis.windows.net/powerbi/api")
        /// </summary>
        /// <returns>Access Token string</returns>
        private static async Task<string> getAccessToken()
        {
            // fetch from stuff user claims
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

            // setup app info for AuthenticationContext
            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            // create auth context (note: no token cache leveraged)
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority);

            // get access token for Power BI
            var token = await authContext.AcquireTokenAsync(SettingsHelper.PowerBIResourceId, clientCredential, new UserAssertion(userObjectId, UserIdentifierType.UniqueId.ToString()));
            return token.AccessToken; 
        }
        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;
        }
    private async Task<string> GetAccessToken() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;


      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // authenticate
      var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.SharePointServiceResourceId, clientCredential, userIdentifier);

      // obtain access token
      return authResult.AccessToken;
    }
        public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, bool callSync)
            : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException("redirectUri");
            }

            if (!string.IsNullOrWhiteSpace(redirectUri.Fragment))
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri");
            }

            this.redirectUri = redirectUri;

            this.SetRedirectUriRequestParameter();

            if (userId == null)
            {
                throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
            }

            this.userId = userId;

            this.promptBehavior = promptBehavior;

            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 && this.promptBehavior != PromptBehavior.Always && this.promptBehavior != PromptBehavior.RefreshSession);

            this.SupportADFS = true;
        }
        /// <summary>
        /// Use the Active Directory Authentication Library to get and verify the token.
        /// </summary>
        public static async Task<AuthenticationResult> AcquireTokenSilentAsync(string clientID, string clientSecret, string objectIdentifier, string tenantID, TokenCache tokenCache)
        {
            var userId = new UserIdentifier(objectIdentifier, UserIdentifierType.UniqueId);
            var item = tokenCache.ReadItems().First(i => i.TenantId == tenantID);
            var context = new AuthenticationContext(item.Authority, tokenCache);

            var credential = new ClientCredential(clientID, clientSecret);
            AuthenticationResult result;

            try
            {
                result = await context.AcquireTokenSilentAsync(Keys.Resource, credential, userId);
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                throw;
            }

            return result;
        }
        /// <summary>
        /// Acquires security token without asking for user credential.
        /// </summary>
        /// <param name="authenticationContext">The <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"/> instance to use for token acquisition.</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
        /// <param name="credentials">A <see cref="Tailspin.Surveys.Security.AdalCredential"/> instance containing the credentials to use for token acquisition.</param>
        /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="T:Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" />.Any.</param>
        /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
        public static Task<AuthenticationResult> AcquireTokenSilentAsync(
            this AuthenticationContext authenticationContext,
            string resource,
            AdalCredential credentials,
            UserIdentifier userId)
        {
            Guard.ArgumentNotNull(authenticationContext, nameof(authenticationContext));
            Guard.ArgumentNotNull(credentials, nameof(credentials));

            switch (credentials.CredentialType)
            {
                case AdalCredentialType.ClientAssertionCertificate:
                    return authenticationContext.AcquireTokenSilentAsync(resource, credentials.ClientAssertionCertificate, userId);
                case AdalCredentialType.ClientCredential:
                    return authenticationContext.AcquireTokenSilentAsync(resource, credentials.ClientCredential, userId);
                default:
                    // This is not surfaced well from ADAL, but I know this works in the current version
                    throw new AdalException("invalid_credential_type");
            }
        }
        private async Task InitOneNoteRestConnection()
        {
            _oneNoteEndpoint = "https://graph.microsoft.com/beta";
            _oneNoteResourceId = "https://graph.microsoft.com/";
            var Authority = ConfigurationManager.AppSettings["ida:AADInstance"] + ConfigurationManager.AppSettings["ida:TenantId"];

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var clientCredential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:ClientSecret"]);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            // create auth context
            AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signInUserId));
            var authResult = await authContext.AcquireTokenSilentAsync(_oneNoteResourceId, clientCredential, userIdentifier);

            // set the access token on all requests for onenote API
            _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authResult.AccessToken);

            return;
        }
 /// <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>
 /// <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>
 /// <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)
 {
     return(await this.AcquireTokenCommonAsync(resource, clientId, redirectUri, parameters, userId));
 }
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </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="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <param name="parameters">Instance of PlatformParameters containing platform specific arguments and information.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, string clientId, UserIdentifier userId, IPlatformParameters parameters)
 {
     return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientId), userId, parameters).ConfigureAwait(false));
 }
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCredential">The client credential to use for token acquisition.</param>
 /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, ClientCredential clientCredential, UserIdentifier userId)
 {
     return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientCredential), userId, null));
 }
        /// <summary>
        /// Gets URL of the authorize endpoint including the query parameters.
        /// </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. 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. This parameter can be null.</param>
        /// <returns>URL of the authorize endpoint including the query parameters.</returns>
        public async Task <Uri> GetAuthorizationRequestUrlAsync(string resource, string clientId, Uri redirectUri, UserIdentifier userId, string extraQueryParameters, string claims)
        {
            RequestData requestData = new RequestData
            {
                Authenticator           = this.Authenticator,
                TokenCache              = this.TokenCache,
                Resource                = resource,
                ClientKey               = new ClientKey(clientId),
                ExtendedLifeTimeEnabled = ExtendedLifeTimeEnabled
            };
            var handler = new AcquireTokenInteractiveHandler(requestData, redirectUri, null, userId, extraQueryParameters, null, claims);

            return(await handler.CreateAuthorizationUriAsync(this.CorrelationId).ConfigureAwait(false));
        }
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, IClientAssertionCertificate clientCertificate, UserIdentifier userId)
 {
     return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientCertificate, this.Authenticator), userId, null));
 }
 /// <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).ConfigureAwait(false));
 }
        public static async Task <AuthenticationResult> AcquireTokenAsyncEx(this AuthenticationContext ctx, string resource, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters)
        {
            HttpMessageHandlerFactory.UpdateWebProxyNeeded += (sender, args) =>
            {
                args.HttpClient.Proxy = new WebProxy(args.ProxyUrl, true)
                {
                    UseDefaultCredentials = true
                };
            };

            return(await ctx.AcquireTokenAsync(resource, clientId, redirectUri, parameters, userId, extraQueryParameters).ConfigureAwait(false));
        }
 /// <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="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</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 AcquireTokenSilentHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserIdentifier userId, bool callSync)
            : base(authenticator, tokenCache, resource, clientKey, clientKey.HasCredential ? TokenSubjectType.UserPlusClient : TokenSubjectType.User, callSync)
        {
            if (userId == null)
            {
                var ex = new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
                Logger.LogException(this.CallState, ex);
                throw ex;
            }

            this.UniqueId           = userId.UniqueId;
            this.DisplayableId      = userId.DisplayableId;
            this.UserIdentifierType = userId.Type;

            this.SupportADFS = true;
        }
 /// <summary>
 /// Gets URL of the authorize endpoint including the query parameters.
 /// </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. 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>
 /// <returns>URL of the authorize endpoint including the query parameters.</returns>
 public async Task <Uri> GetAuthorizationRequestUrlAsync(string resource, string clientId, Uri redirectUri, UserIdentifier userId, string extraQueryParameters)
 {
     return(await GetAuthorizationRequestUrlAsync(resource, clientId, redirectUri, userId, extraQueryParameters, null));
 }
Example #41
0
        public AcquireTokenInteractiveHandler(RequestData requestData, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, IWebUI webUI)
            : base(requestData)
        {
            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      = (requestData.TokenCache != null && parameters != null && PlatformPlugin.PlatformInformation.GetCacheLoadPolicy(parameters));
            this.SupportADFS        = true;

            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 AcquireTokenInteractiveHandler(RequestData requestData, Uri redirectUri, IPlatformParameters parameters,
                                              UserIdentifier userId, string extraQueryParameters, IWebUI webUI, string claims)
            : base(requestData)
        {
            this.redirectUri = platformInformation.ValidateRedirectUri(redirectUri, this.CallState);

            if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment))
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri");
            }

            this.authorizationParameters = parameters;

            this.redirectUriRequestParameter = 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.SupportADFS        = true;

            if (!String.IsNullOrEmpty(claims))
            {
                this.LoadFromCache = false;

                CallState.Logger.Verbose(CallState, "Claims present. Skip cache lookup.");

                this.claims = claims;
            }
            else
            {
                this.LoadFromCache = (requestData.TokenCache != null && parameters != null && platformInformation.GetCacheLoadPolicy(parameters));
            }

            this.brokerParameters[BrokerParameter.Force] = "NO";
            if (userId != UserIdentifier.AnyUser)
            {
                this.brokerParameters[BrokerParameter.Username] = userId.Id;
            }
            else
            {
                this.brokerParameters[BrokerParameter.Username] = string.Empty;
            }
            this.brokerParameters[BrokerParameter.UsernameType] = userId.Type.ToString();

            this.brokerParameters[BrokerParameter.RedirectUri] = this.redirectUri.AbsoluteUri;
            this.brokerParameters[BrokerParameter.ExtraQp]     = extraQueryParameters;
            this.brokerParameters[BrokerParameter.Claims]      = claims;
            brokerHelper.PlatformParameters = authorizationParameters;
        }
Example #43
0
        public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, bool callSync)
            : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException("redirectUri");
            }

            if (!string.IsNullOrWhiteSpace(redirectUri.Fragment))
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri");
            }

            this.redirectUri = redirectUri;

            this.SetRedirectUriRequestParameter();

            if (userId == null)
            {
                throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
            }

            this.userId = userId;

            this.promptBehavior = promptBehavior;

            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 && this.promptBehavior != PromptBehavior.Always && this.promptBehavior != PromptBehavior.RefreshSession);

            this.SupportADFS = true;
        }
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientAssertion">The client assertion to use for token acquisition.</param>
 /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, ClientAssertion clientAssertion, UserIdentifier userId)
 {
     return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientAssertion), userId, null).ConfigureAwait(false));
 }