當前位置: 首頁>>代碼示例>>C#>>正文


C# ActiveDirectory.AuthenticationContext類代碼示例

本文整理匯總了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext的典型用法代碼示例。如果您正苦於以下問題:C# AuthenticationContext類的具體用法?C# AuthenticationContext怎麽用?C# AuthenticationContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AuthenticationContext類屬於Microsoft.IdentityModel.Clients.ActiveDirectory命名空間,在下文中一共展示了AuthenticationContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: RetrieveTokenAsync

 /// <summary>
 /// Retrieves a new auth token from AAD.
 /// </summary>
 /// <param name="authUrl">The root of the authority url.</param>
 /// <param name="tenantDomain">The domain name of the Azure tenant as the second part of the authority url.</param>
 /// <param name="targetServiceUrl">The url of the service that should be accessed. Be sure to check trailing slashes!</param>
 /// <param name="clientId">The unique client id as it is configured in Azure Portal.</param>
 /// <param name="appKey">This value is optional and contains the App-Key-Secret if it is configured in azure portal.</param>
 /// <param name="redirectUrl">The redirect url as it is configured in Azure Portal.</param>
 /// <returns>The authentication token.</returns>
 public static async Task<string> RetrieveTokenAsync(string authUrl, string tenantDomain, string targetServiceUrl, string clientId, Uri redirectUrl, string appKey = null)
 {
     var authenticationContext = new AuthenticationContext($"{authUrl}/{tenantDomain}");
     try
     {
         AuthenticationResult result = null;                
         if (appKey.IsNullOrEmpty())
         {
             // use user auth
             var parameters = new PlatformParameters(PromptBehavior.Auto);
             result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientId, redirectUrl, parameters).ConfigureAwait(false);
         }
         else
         {
             // use key auth
             var clientCredential = new ClientCredential(clientId, appKey);
             result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientCredential).ConfigureAwait(false);
         }
         if (result == null)
         {
             throw new InvalidOperationException("Failed to obtain the JWT token");
         }
         // store token for reuse
         return result.AccessToken;
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException("Could not retrieve token.", ex);
     }
 }
開發者ID:codingfreak,項目名稱:cfUtils,代碼行數:40,代碼來源:TokenUtil.cs

示例2: GetAccessToken

        public string GetAccessToken()
        {
            ApplicationDbContext db = new ApplicationDbContext();
              string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
              string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
              string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
              string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];

              string Authority = aadInstance + tenantId;

              string claimIdName = ClaimTypes.NameIdentifier;
              string claimIdTenantId = "http://schemas.microsoft.com/identity/claims/tenantid";
              string claimIdUserId = "http://schemas.microsoft.com/identity/claims/objectidentifier";

              ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;

              string signedInUserID = currentUserClaims.FindFirst(claimIdName).Value;
              string tenantID = currentUserClaims.FindFirst(claimIdTenantId).Value;
              string userObjectID = currentUserClaims.FindFirst(claimIdUserId).Value;

              // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
              ClientCredential clientcred = new ClientCredential(clientId, appKey);
              // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
              AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
              AuthenticationResult authenticationResult =
            authenticationContext.AcquireTokenSilentAsync(resource,
                                                      clientcred,
                                                      new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)).Result;
              return authenticationResult.AccessToken;
        }
開發者ID:CriticalPathTraining,項目名稱:GOA365,代碼行數:30,代碼來源:UserProfileController.cs

示例3: GetADTokenForRequests

        /// <summary>
        /// Gets the AD token for the requests, for the received customer tenant.
        /// </summary>
        public async Task<AuthorizationToken> GetADTokenForRequests(string customerTenant)
        {
            if (_tokenForRequests != null)
            {
                // already initialized
                return _tokenForRequests;
            }

            AuthenticationContext _authenticationContext = new AuthenticationContext(string.Format(Constants.AAD_INSTANCE,
                customerTenant));

            UserCredential _userCredential = new UserCredential(Constants.CSP_SERVICE_USERNAME,
                Constants.CSP_SERVICE_PASSWORD);

            // else. Initialize and return
            AuthenticationResult authenticationResult = await _authenticationContext.AcquireTokenAsync(
                  Constants.GRAPH_RESOURCE_URL,
                  Constants.AZURE_AD_APP_ID_NATIVE_APP,
                  _userCredential);

            _tokenForRequests = new AuthorizationToken(authenticationResult.AccessToken,
             authenticationResult.ExpiresOn.DateTime);

            return _tokenForRequests;
        }
開發者ID:createitpt,項目名稱:Create.CSP.GitHub.ScenarioEndToEnd,代碼行數:28,代碼來源:AzureADGraphApiHelper.cs

示例4: ConfigureAuth

    public void ConfigureAuth(IAppBuilder app) {
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
      app.UseCookieAuthentication(new CookieAuthenticationOptions());

      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
        ClientId = SettingsHelper.ClientId,
        Authority = SettingsHelper.AzureADAuthority,
        Notifications = new OpenIdConnectAuthenticationNotifications() {
          AuthorizationCodeReceived = (context) => {
            string code = context.Code;

            ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;

            EFADALTokenCache cache = new EFADALTokenCache(userObjectId);
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, cache);

            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

            return Task.FromResult(0);
          },
          AuthenticationFailed = (context) => {
            context.HandleResponse();
            return Task.FromResult(0);
          }
        },
        TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
          ValidateIssuer = false
        }
      });
    }
開發者ID:modulexcite,項目名稱:TrainingContent,代碼行數:32,代碼來源:Startup.Auth.cs

示例5: AcquireToken

 public static string AcquireToken(string userObjectId)
 {
     ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
     AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
     AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
     return result.AccessToken;
 }
開發者ID:bstearns,項目名稱:active-directory-dotnet-webapp-groupclaims,代碼行數:7,代碼來源:GraphHelper.cs

示例6: EnsureClientCreated

  /// <summary>
  /// Checks that an OutlookServicesClient object is available. 
  /// </summary>
  /// <returns>The OutlookServicesClient object. </returns>
  public static async Task<OutlookServicesClient> EnsureClientCreated() {
    AuthenticationContext = new AuthenticationContext(CommonAuthority);

    if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) {
      // Bind the AuthenticationContext to the authority that sourced the token in the cache 
      // this is needed for the cache to work when asking for a token from that authority 
      // (the common endpoint never triggers cache hits) 
      string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority;
      AuthenticationContext = new AuthenticationContext(cachedAuthority);

    }

    // Create a DiscoveryClient using the discovery endpoint Uri.  
    DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri,
        async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId));

    // Now get the capability that you are interested in.
    var result = await discovery.DiscoverCapabilityAsync("Mail");

    var client = new OutlookServicesClient(
        result.ServiceEndpointUri,
        async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId));

    return client;
  }
開發者ID:chrissimusokwe,項目名稱:TrainingContent,代碼行數:29,代碼來源:MyEventsRepository.cs

示例7: MainAsync

        static async Task MainAsync(string[] args)
        {
            var keyClient = new KeyVaultClient((authority, resource, scope) =>
            {
                var adCredential = new ClientCredential(applicationId, applicationSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
            });

            // Get the key details
            var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
            var key = await keyClient.GetKeyAsync(keyIdentifier);
            var publicKey = Convert.ToBase64String(key.Key.N);

            using (var rsa = new RSACryptoServiceProvider())
            {
                var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
                rsa.ImportParameters(p);
                var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
                
                // Encrypt and Decrypt
                var encryptedText = rsa.Encrypt(byteData, true);
                var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
                var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);

                // Sign and Verify
                var hasher = new SHA256CryptoServiceProvider();
                var digest = hasher.ComputeHash(byteData);
                var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
                var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
            }
        }
開發者ID:nyghtrocker,項目名稱:Blog,代碼行數:32,代碼來源:Program.cs

示例8: AccessToken

        //Get access token:
        // To call a Data Catalog REST operation, create an instance of AuthenticationContext and call AcquireToken
        // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
        // To install the Active Directory Authentication Library NuGet package in Visual Studio,
        //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the NuGet Package Manager Console.
        static AuthenticationResult AccessToken()
        {
            if (authResult == null)
            {
                //Resource Uri for Data Catalog API
                string resourceUri = "https://datacatalog.azure.com";

                //To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
                string clientId = clientIDFromAzureAppRegistration;

                //A redirect uri gives AAD more details about the specific application that it will authenticate.
                //Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app.
                string redirectUri = "https://login.live.com/oauth20_desktop.srf";

                // Create an instance of AuthenticationContext to acquire an Azure access token
                // OAuth2 authority Uri
                string authorityUri = "https://login.windows.net/common/oauth2/authorize";
                AuthenticationContext authContext = new AuthenticationContext(authorityUri);

                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                //  AcquireToken takes a Client Id that Azure AD creates when you register your client app.
                authResult = authContext.AcquireToken(resourceUri, clientId, new Uri(redirectUri), PromptBehavior.RefreshSession);
            }

            return authResult;
        }
開發者ID:torevor,項目名稱:data-catalog-dotnet-get-started,代碼行數:31,代碼來源:Program.cs

示例9: Button_Click

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string result = string.Empty;
            // Get token
            AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/SalesApplication.onmicrosoft.com");//the 'App ID URI' of the secured resource/API trying to access as configured in AAD

            AuthenticationResult ar =
              ac.AcquireToken("https://SalesApplication.onmicrosoft.com/WebAPIDemo", //the "name" of the secured resource/API trying to access as configured in AAD ('App ID URI')
              "5685ff14-3fb8-4785-a78e-6f81219b39f8",// the 'client ID' for this client application as configured in AAD
              new Uri("https://SalesApplication.onmicrosoft.com/myWebAPInativeclient"));// the redirect URI for this client application as configured in AAD

            // http://goo.gl/Ypb6yv
            // the following generates a security exception since we don't have a valid certificate
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation);

            // Call Web API
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", ar.AccessToken);

            HttpResponseMessage response = httpClient.GetAsync("https://localhost:44304/api/Values").Result;

            // display the result
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
                MessageBox.Show(result);
            }
            else
            {
                result = response.Content.ReadAsStringAsync().Result;
                MessageBox.Show(result, response.StatusCode.ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
開發者ID:TheFastCat,項目名稱:AzureActiveDirectoryAuthentication,代碼行數:34,代碼來源:MainWindow.xaml.cs

示例10: Main

        static void Main(string[] args)
        {
            /// Azure AD WebApi's APP ID URL
            string resource = "";

            /// Azure AD WebApi's Client ID 
            string clientId = "";

            /// Azure AD User's credentials
            string userName = "";
            string userPassword = "";

            /// Web API's URL
            string apiUrl = "http://localhost:3672/api/Test";

            var user = new UserCredential(userName, userPassword);

            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");

            /// Get an Access Token to Access the Web API on behalf of the user
            AuthenticationResult authResult = authContext.AcquireTokenAsync(resource, clientId, user).Result;

            /// Call WebAPI passing Access token on header
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            /// Get the result 
            HttpResponseMessage response = client.GetAsync(apiUrl).Result;
            string text = response.Content.ReadAsStringAsync().Result;
        }
開發者ID:tandis,項目名稱:PnP,代碼行數:30,代碼來源:Program.cs

示例11: btnCallDirect_Click

        private async void btnCallDirect_Click(object sender, EventArgs e)
        {

            try
            {
                authContext = new AuthenticationContext(authority);
                AuthenticationResult authResult = authContext.AcquireToken(apiResourceId, clientId, redirectUri);

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                HttpResponseMessage response = await client.GetAsync(apiBaseAddress + "api/add?a=100&b=100");
                response.EnsureSuccessStatusCode();

                string responseString = await response.Content.ReadAsStringAsync();

                MessageBox.Show(responseString);
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
開發者ID:PaulBaars,項目名稱:TwoCents,代碼行數:28,代碼來源:CalculatorClientForm.cs

示例12: GetAccessToken

    protected static void GetAccessToken() {

      // shared login authority for all Office 365 tenants
      string authority = "https://login.microsoftonline.com/common";

      // create new authentication context 
      var authenticationContext = new AuthenticationContext(authority);

      // create URI for target resource
      string urlAzureGraphApi = "https://graph.windows.net/";
      string tenantDomain = "SharePointConfessions.onMicrosoft.com";
      Uri uriAzureGraphApiResource = new Uri(urlAzureGraphApi + tenantDomain);

      // 
      string clientID = "128d1e44-5e55-4027-96e6-bc36e5b10a0a";
      string redirectUri = "https://localhost/AzureGraphNativeClient";


      // use authentication context to trigger user sign-in and return access token 
      var userAuthnResult = authenticationContext.AcquireToken(urlAzureGraphApi,
                                                               clientID,
                                                               new Uri(redirectUri),
                                                               PromptBehavior.RefreshSession);
      // cache access token in AccessToken field
      AccessToken = userAuthnResult.AccessToken;


    }
開發者ID:CriticalPathTraining,項目名稱:DSU365,代碼行數:28,代碼來源:Program.cs

示例13: ConfigureAuth

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = _appConfig.ClientID,
                    Authority = Constants.Authentication.CommonAuthority,
                    PostLogoutRedirectUri = _appConfig.PostLogoutRedirectURI,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                        // we inject our own multitenant validation logic
                        ValidateIssuer = false,
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            ClientCredential credential = new ClientCredential(_appConfig.ClientID,_appConfig.ClientSecret);

                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new ADALTokenCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                        code,
                                        new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                        credential,
                                        Constants.Authentication.GraphServiceUrl);

                            return Task.FromResult(0);
                        },
                        RedirectToIdentityProvider = (context) =>
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = (context) =>
                        {
                            System.Diagnostics.Trace.TraceError(context.Exception.ToString());
                            string redirectPath = string.Format("/Error/?errorMessage={0}", context.Exception.Message);
                            context.OwinContext.Response.Redirect(redirectPath);
                           // context.OwinContext.Response.Redirect("/Error/Index");
                            context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });
        }
開發者ID:RapidCircle,項目名稱:PnP-Tools,代碼行數:60,代碼來源:Startup.Auth.cs

示例14: UserTokenProvider

        /// <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;
        }
開發者ID:Ranjana1996,項目名稱:autorest,代碼行數:33,代碼來源:UserTokenProvider.cs

示例15: GetAccessToken

 private async Task<AuthenticationResult> GetAccessToken()
 {
     AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
     var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
     AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey];
     return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource);
 }
開發者ID:martinkearn,項目名稱:DontPanic,代碼行數:7,代碼來源:UserController.cs


注:本文中的Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。