当前位置: 首页>>代码示例>>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;未经允许,请勿转载。