Exemple #1
2
 /// <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);
     }
 }
Exemple #2
1
        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);
            }
        }
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

            ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
            var authenticationContext         = new AuthenticationContext(authorityUriv2, true);
            var authContext          = new AuthenticationContext(authorityUriv2);
            var authenticationResult = authContext.AcquireTokenAsync(resource, clientId, new Uri(ClientRedirectUrl), new PlatformParameters(PromptBehavior.Auto)).GetAwaiter().GetResult();

            accessToken = authenticationResult.AccessToken;

            //var clientBC = new RestClient("https://api.businesscentral.dynamics.com/v2.0/Production/api/CertTech/Integrations/v1.0");
            var clientBC = new RestClient("https://api.businesscentral.dynamics.com/v2.0/Production/api/CertTech/Integrations/v1.0/companies");

            clientBC.Timeout = -1;
            var requestBC = new RestRequest(Method.GET);

            requestBC.AddHeader("Authorization", "Bearer " + accessToken);
            IRestResponse responseBC = clientBC.Execute(requestBC);

            bcResponse = responseBC.Content;
            object resposeDataBC = JsonConvert.DeserializeObject(bcResponse);

            Console.Write(resposeDataBC);
            Console.ReadKey();
        }
        public async Task JsonWebTokenWithX509PublicCertSendX5CTestAsync()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            var validCertClaim = "\"x5c\":\"" + Convert.ToBase64String(certificate.GetRawCertData());

            //Check for x5c claim
            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            //Check for empty x5c claim
            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            context.TokenCache.Clear();
            result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);
        }
        public async Task JsonWebTokenWithX509PublicCertClaimTest()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            var validCertClaim = "\"x5c\":\"" + Convert.ToBase64String(certificate.GetRawCertData());

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.TenantSpecificAuthority))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"access_token\":\"some-access-token\"}")
                },
                AdditionalRequestValidation = request =>
                {
                    var requestContent = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var formsData      = EncodingHelper.ParseKeyValueList(requestContent, '&', true, null);

                    // Check presence of client_assertion in request
                    string encodedJwt;
                    Assert.IsTrue(formsData.TryGetValue("client_assertion", out encodedJwt), "Missing client_assertion from request");

                    // Check presence of x5c cert claim. It should not exist.
                    var jwtHeader = EncodingHelper.UrlDecode(encodedJwt.Split('.')[0]);
                    Assert.IsTrue(!jwtHeader.Contains("\"x5c\":"));
                }
            });

            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion);

            Assert.IsNotNull(result.AccessToken);
        }
Exemple #6
0
        // Redeem code for token asynchronosly for performance, must not do synchronous call for Production
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            Startup.LastContext = context;
            code      = context.Code;
            returnUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            // Token Service appKey is required to authenticate with Azure AD for redeeming the authorization code
            // Note that the code is returned to LE-SfBApp, but the JavaScript client cannot make use of it
            ClientCredential credential = new ClientCredential(clientId, appKey);

            // userObjectID is the objectGUID of the O365 user in Azure AD
            string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // intialize with common to retrieve MRRT, index Cache with both user GUID and resource url due to UCWA usage pattern
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Startup.Authority, Startup.sessionCache);
            AuthContext authContext = new AuthContext(Authority,
                                                      new DistributedTokenCache(cacheconnStr, userObjectID));

            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, returnUri, credential, ucwaResourceUrl);

            // Azure AD schema change
            // 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(aadInstance + tenantID, new ADALTokenCache(signedInUserID));

            Startup.accessToken  = result.AccessToken;
            Startup.refreshToken = result.RefreshToken;
            Startup.idToken      = result.IdToken;
        }
Exemple #7
0
    /// <summary>
    /// get crm service client
    /// </summary>
    public void GetCrmServiceClient()
    {
        if (string.IsNullOrWhiteSpace(this.crmConnection))
        {
            this.ReadKeyVault();
        }

        try
        {
            var credentials = new ClientCredential(this.appClientID, this.appClientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(this.authority);
            var result = authContext.AcquireTokenAsync(this.resourceURL, credentials).Result;
            var accesToken = result.AccessToken;
            Uri serviceUrl = new Uri(this.CRMConnection);

            using (sdkService = new OrganizationWebProxyClient(serviceUrl, false))
            {
                sdkService.HeaderToken = accesToken;

                this.ServiceClient = (IOrganizationService)sdkService != null ? (IOrganizationService)sdkService : null;
            }

        }
        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
        {
            this.logger.Error("CRM Connection Issue: ", ex);
            throw;
        }
        catch (Exception ex)
        {
            this.logger.Error("CRM Connection Issue: ", ex);
            throw;
        }
    }
        /// <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;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Redirect uri must match the redirect_uri used when requesting Authorization code.
            string redirectUri = Properties.Settings.Default.RedirectUrl;
            string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
           
            // Get the auth code
            string code = Request.Params.GetValues(0)[0];
            
            // Get auth token from auth code       
            TokenCache TC = new TokenCache();

            AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);

            ClientCredential cc = new ClientCredential
                (Properties.Settings.Default.ClientID,
                Properties.Settings.Default.ClientSecretKey);

            AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);

            //Set Session "authResult" index string to the AuthenticationResult
            Session["authResult"] = AR;

            //Redirect back to Default.aspx
            Response.Redirect("/Default.aspx");
        }
Exemple #10
0
        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;
        }
        private async Task <AuthenticationResult> GetToken()
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync(new Uri(Configuration["CRMConnection:ServiceUrl"])).Result;

                string authorityUrl = ap.Authority.Remove(ap.Authority.IndexOf("/oauth2/authorize"));

                AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authorityUrl, false);

                CRMOrgURL = ap.Resource;

                try
                {
                    return(await GetAccessToken(authorityUrl, CRMOrgURL, Configuration["CRMConnection:ClientID"], Configuration["CRMConnection:ClientSecret"]));
                }
                catch (AdalException e)
                {
                    throw e;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var userCredential        = new ActiveDirectory.UserCredential();

                ActiveDirectory.AuthenticationResult result = await AdalExtentions.AcquireTokenAsync(authenticationContext,
                                                                                                     resource,
                                                                                                     clientId,
                                                                                                     userCredential);

                return(new Result(result));
            }
            catch (ActiveDirectory.AdalException exception)
            {
                throw new AuthenticationException(exception);
            }
        }
Exemple #13
0
        private JwtSecurityToken GetJwtSecurityToken()
        {
            IOwinContext          owinContext     = HttpContext.GetOwinContext();
            string                userObjectID    = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
            NaiveSessionCache     cache           = new NaiveSessionCache(userObjectID);
            AuthenticationContext authContext     = new AuthenticationContext(Configuration.Authority, cache);
            TokenCacheItem        kdAPITokenCache = authContext.TokenCache.ReadItems().Where(c => c.Resource == Configuration.KdResourceId).FirstOrDefault();

            if (kdAPITokenCache == null)
            {
                authContext.TokenCache.Clear();
                ViewBag.ErrorMessage = "AuthorizationRequired";
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                return(null);
            }

            return(new JwtSecurityToken(kdAPITokenCache.AccessToken));
        }
        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;
        }
        public ICustomActivityResult Execute()
        {
            string Message               = string.Empty;
            string authContextURL        = "https://login.windows.net/" + tenantId;
            var    authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authContextURL);
            var    credential            = new ClientCredential(clientId, clientSecret);
            var    result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;

            if (result == null)
            {
                Message = "Failed to obtain the JWT token";
                return(this.GenerateActivityResult(Message));
            }
            string         token   = result.AccessToken;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Compute/snapshots/" + snapshotName + "?api-version=2018-06-01");

            request.Method = "DELETE";
            request.Headers["Authorization"] = "Bearer " + token;
            request.ContentType = "application/json";
            try
            {
                request.GetRequestStream();
                var httpResponse = (HttpWebResponse)request.GetResponse();
                httpResponse.GetResponseStream();
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                return(this.GenerateActivityResult(Message));
            }
            Message = "Success";
            return(this.GenerateActivityResult(Message));
        }
        public async Task AutoPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" }
                }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());
            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);
            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
    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();
    }
        public static string GetTokenForSpn(string authority, string audience, string domain, string applicationId, string secret)
        {
            var context = new AuthenticationContext(EnsureTrailingSlash(authority) + domain, true, TokenCache.DefaultShared);
            var authResult = context.AcquireToken(audience, new ClientCredential(applicationId, secret));

            return authResult.AccessToken;
        }
        /// <summary>
        /// Methods for getting a token from ACS 
        /// Updated 10/21, to use Active Directory Authn Library (ADAL) 
        /// Method uses OAuth Authorization Code Grant flow (3-legged OAuth)
        /// ADAL package avaialble from https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/1.0.0
        /// </summary>

        public static AADJWTToken GetAuthorizationToken(string tenantName, string appPrincipalId, Uri appUri)
        {

            string authString = String.Format(StringConstants.AzureADSTSURL, tenantName);
            AuthenticationContext authenticationContext = new AuthenticationContext(authString);
            try
            {
                AuthenticationResult authenticationResult = authenticationContext.AcquireToken(StringConstants.GraphPrincipalId.ToString(), appPrincipalId, appUri);
                if (authenticationResult != null)
                {
                    AADJWTToken token = new AADJWTToken();
                    token.AccessToken = authenticationResult.AccessToken;
                    token.TokenType = authenticationResult.AccessTokenType;
                    token.ExpiresOn = authenticationResult.ExpiresOn.UtcTicks;
                    token.AdalToken = authenticationResult;
                    return token;
                }
                else
                    return null;
            }
            catch (Exception e)
            {
                //Console.WriteLine("Exception: " + e.Message + " " + e.InnerException);
                return null;
            }
        }
        public async Task UnknownUserRealmDiscoveryTestAsync()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);
            await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Unknown\",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            var ex = AssertException.TaskThrows <AdalException>(() =>
                                                                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                          new UserPasswordCredential(TestConstants.DefaultDisplayableId,
                                                                                                                     TestConstants.DefaultPassword)));

            Assert.AreEqual(AdalError.UnknownUserType, ex.ErrorCode);
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
            Assert.AreEqual(0, context.TokenCache.Count);
        }
    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;
    }
 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);
 }
        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);
            }


        }
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    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(clientId, appKey);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                            AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                            return Task.FromResult(0);
                        }
                    }
                });
        }
Exemple #25
0
        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);
                        }
                    }
                });
        }
    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;


    }
        /// <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;
        }
Exemple #28
0
        private async Task AddRoles(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            var context           = new Adal.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
            var clientCredentials = new Adal.ClientCredential(GraphClientId, GraphClientSecret);
            var token             = await context.AcquireTokenAsync("https://graph.windows.net/", clientCredentials);

            var userId = arg.AuthenticationTicket.Identity.Claims
                         .First(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")
                         .Value;

            HttpClient http = new HttpClient();
            string     url  = "https://graph.windows.net/b2ctestdes.onmicrosoft.com/users/" + userId + "/memberOf?api-version=1.6";

            // Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
            HttpResponseMessage response = await http.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                dynamic groups = JObject.Parse(result);

                foreach (var group in groups.value)
                {
                    string groupName = group.displayName;

                    arg.AuthenticationTicket.Identity.AddClaim(
                        new Claim(ClaimTypes.Role, groupName));
                }
            }
        }
      /// <summary>
      /// Gets the access token
      /// </summary>
      /// <param name="authority"> Authority </param>
      /// <param name="resource"> Resource </param>
      /// <param name="scope"> scope </param>
      /// <returns> token </returns>
      public async Task<string> GetAccessToken(string authority, string resource, string scope)
      {
         var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
         var result = await context.AcquireTokenAsync(resource, _credential);

         return result.AccessToken;
      }
    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;

    }
        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);
            }
        }
        // GET: MyFiles
        public async Task<ActionResult> Index()
        {
            List<MyFile> myFiles = new List<MyFile>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                SharePointClient spClient = new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var filesResult = await spClient.Files.ExecuteAsync();

                do
                {
                    var files = filesResult.CurrentPage.OfType<File>();

                    foreach (var file in files)
                    {
                        myFiles.Add(new MyFile { Name = file.Name });
                    }

                    filesResult = await filesResult.GetNextPageAsync();

                } while (filesResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(myFiles);
        }
Exemple #33
0
        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;
        }
 /// <summary>
 /// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode.
 /// </summary>
 /// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param>
 /// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns>
 public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode)
 {
     var authenticationContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID));
     var clientCredential      = new ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY);
     var authenticationResult  = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential);
     return new UserIdentity(authenticationResult.UserInfo);
 }
        /// <summary>
        /// Returns token (requires user input)
        /// </summary>
        /// <returns></returns>
        public static AuthenticationResult GetToken(string authEndpoint, string tenant, string clientId)
        {
            var adalWinFormType = typeof(WebBrowserNavigateErrorEventArgs);
            Trace.WriteLine("Getting a random type from \'Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms\' to force it be deployed by mstest");

            AuthenticationResult result = null;
            var thread = new Thread(() =>
            {
                try
                {
                    var context = new AuthenticationContext(Path.Combine(authEndpoint, tenant));

                    result = context.AcquireToken(
                        resource: "https://management.core.windows.net/",
                        clientId: clientId,
                        redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"),
                        promptBehavior: PromptBehavior.Auto);
                }
                catch (Exception threadEx)
                {
                    Console.WriteLine(threadEx.Message);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();
            thread.Join();

            return result;

        }
    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;
    }
        //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;
        }
        public void UserRealmDiscoveryFailsTest()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Bad request received")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            var ex = AssertException.TaskThrows <AdalException>(() =>
                                                                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                          new UserPasswordCredential(TestConstants.DefaultDisplayableId,
                                                                                                                     TestConstants.DefaultPassword)));

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
            Assert.AreEqual(0, context.TokenCache.Count);

            //To be addressed in a later fix
            //Assert.AreEqual(((AdalException)ex.InnerException.InnerException).ErrorCode, AdalError.UserRealmDiscoveryFailed);
        }
 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;
 }
    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;
        });
    }
  /// <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;
  }
        /// <summary>
        /// acquires a <see cref="TokenPair"/> from the authority via an interactive user logon 
        /// prompt.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="redirectUri">
        /// Address to return to upon receiving a response from the authority.
        /// </param>
        /// <param name="queryParameters">
        /// Optional: appended as-is to the query string in the HTTP authentication request to the
        /// authority.
        /// </param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public TokenPair AcquireToken(Uri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(redirectUri != null, "The redirectUri parameter is null");
            Debug.Assert(redirectUri.IsAbsoluteUri, "The redirectUri parameter is not an absolute Uri");

            Trace.WriteLine("AzureAuthority::AcquireToken");

            TokenPair tokens = null;
            queryParameters = queryParameters ?? String.Empty;

            try
            {
                Trace.WriteLine(String.Format("   authority host url = '{0}'.", AuthorityHostUrl));

                AuthenticationContext authCtx = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = authCtx.AcquireToken(resource, clientId, redirectUri, PromptBehavior.Always, UserIdentifier.AnyUser, queryParameters);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }
Exemple #43
0
        /// <summary>
        /// Authenticates the specified request message.
        /// This method will be called any time there is an outbound request.
        /// In this case we are using the Microsoft.IdentityModel.Clients.ActiveDirectory library
        /// to stamp the outbound http request with the OAuth 2.0 token using an AAD application id
        /// and application secret.  Alternatively, this method can support certificate validation.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="tenant">The tenant.</param>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        public async Task AuthenticateOutboundRequestAsync(HttpRequestMessage request, string tenant)
        {
            const string schema           = "Bearer";
            const string replaceString    = "{tenant}";
            const string oauthV2TokenLink = "https://login.microsoftonline.com/{tenant}";
            const string resource         = "https://graph.microsoft.com";

            // If no tenant was specified, we craft the token link using the common tenant.
            // https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints
            tenant = string.IsNullOrWhiteSpace(tenant) ? "common" : tenant;
            var tokenLink = oauthV2TokenLink.Replace(replaceString, tenant);

            this.GraphLogger.Info("AuthenticationProvider: Generating OAuth token.");
            var context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(tokenLink);
            var creds   = new ClientCredential(this.appId, this.appSecret);

            AuthenticationResult result;

            try
            {
                result = await this.AcquireTokenWithRetryAsync(context, resource, creds, attempts : 3).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                this.GraphLogger.Error(ex, $"Failed to generate token for client: {this.appId}");
                throw;
            }

            this.GraphLogger.Info($"AuthenticationProvider: Generated OAuth token. Expires in {result.ExpiresOn.Subtract(DateTimeOffset.UtcNow).TotalMinutes} minutes.");

            request.Headers.Authorization = new AuthenticationHeaderValue(schema, result.AccessToken);
        }
        public void ForcePromptForNeverPromptBehaviorTest()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
            });

            var exc = AssertException.TaskThrows <AdalServiceException>(() =>
                                                                        context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                                  TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Never)));

            Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode);
            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        private async Task <AuthenticationResult> GetAppOnlyAccessToken(string resource, string tenantId)
        {
            string authority = appConfig.AuthorizationUri.Replace("common", tenantId);

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(
                authority,
                false);

            string certfile = Server.MapPath(appConfig.ClientCertificatePfx);

            X509Certificate2 cert = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            // ADAL new ... (in Beta, might change)
            // ClientAssertionCertificate cac = new ClientAssertionCertificate(
            //    appConfig.ClientId,
            //    cert.GetRawCertData(),
            //    appConfig.ClientCertificatePfxPassword);

            // ADAL current released (2.12.111071459)
            ClientAssertionCertificate cac = new ClientAssertionCertificate(
                appConfig.ClientId, cert);

            var authenticationResult = await authenticationContext.AcquireTokenAsync(
                resource,
                cac);

            return(authenticationResult);
        }
        public async Task AutoPromptBehaviorWithTokenInCacheTestAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
    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
        }
      });
    }
Exemple #48
0
        private async Task AdalLogin(bool forcePrompt)
        {
            var spUri = new Uri($"{txtSiteFor2FA.Text}");

            string       resourceUri = spUri.Scheme + "://" + spUri.Authority;
            const string clientId    = "9bc3ab49-b65d-410a-85ad-de819febfddc";
            const string redirectUri = "https://oauth.spops.microsoft.com/";

            ADAL.AuthenticationResult authenticationResult;

            if (authContext == null || forcePrompt)
            {
                ADAL.TokenCache cache = new ADAL.TokenCache();
                authContext = new ADAL.AuthenticationContext(AuthorityUri, cache);
            }
            try
            {
                if (forcePrompt)
                {
                    throw new ADAL.AdalSilentTokenAcquisitionException();
                }
                authenticationResult = await authContext.AcquireTokenSilentAsync(resourceUri, clientId);
            }
            catch (ADAL.AdalSilentTokenAcquisitionException)
            {
                authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always, null), ADAL.UserIdentifier.AnyUser, null, null);
            }

            options.AccessToken = authenticationResult.AccessToken;
            accessTokenObtained = true;
        }
        public async Task AcquireTokenWithValidTokenInCache_ReturnsCachedTokenAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                         new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.IsNotNull(result.UserInfo);

            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        //
        // GET: /UserProfile/
        public async Task <ActionResult> Index()
        {
            //
            // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API.
            //
            UserProfile      profile;
            string           jwtToken     = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsJwtToken).Value;
            JwtSecurityToken token        = new JwtSecurityToken(jwtToken);
            string           userObjectID = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsObjectidentifier).Value;

            AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, new NaiveSessionCache(userObjectID));

            try
            {
                ActiveDirectoryClient activeDirectoryClient = Factory.GetActiveDirectoryClientAsApplication(jwtToken);
                User userProfile = (User)await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync();

                List <string> membergroups = (await userProfile.GetMemberGroupsAsync(false)).ToList();
                var           groups       = await activeDirectoryClient.Groups.ExecuteAsync();

                profile              = new UserProfile();
                profile.Token        = token;
                profile.MemberGroups = membergroups;
                profile.AllGroups    = groups.CurrentPage;
                profile.User         = userProfile;
                return(View(profile));
            }
            catch (Exception)
            {
                //
                // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                //
                var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Configuration.GraphResourceId);
                foreach (TokenCacheItem tci in todoTokens)
                {
                    authContext.TokenCache.DeleteItem(tci);
                }

                //
                // If refresh is set to true, the user has clicked the link to be authorized again.
                //
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                profile = new UserProfile();
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View(profile));
            }
        }
Exemple #51
0
        private static async Task <string> GetNewToken(
            ILogger logger,
            AppSettings appSettings)
        {
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(appSettings.Authority);

            return((await GetResultsUsingDeviceCode(authContext, appSettings)).AccessToken);
        }
        public static async Task <string> GetAccessToken(string azureTenantId, string clientId, string redirectUri)
        {
            var context     = new AuthenticationContext("https://login.windows.net/" + tenantId);
            var credential  = new ClientCredential(appId, appSecret);
            var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);

            return(tokenResult.AccessToken);
        }
Exemple #53
0
        private async Task <AuthenticationResult> GetTokenForPBIEmbedded()
        {
            UserPasswordCredential credentials = new UserPasswordCredential(username, password);

            var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);

            return(await authenticationContext.AcquireTokenAsync(pbiApiResourceUrl, clientId, credentials));
        }
        public static string GetToken(string clientId, string clientSecret, string authority, string resourceUrl)
        {
            ClientCredential credentials = new ClientCredential(clientId, clientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
            var result      = authContext.AcquireTokenAsync(resourceUrl, credentials).Result;

            return(result.AccessToken);
        }
Exemple #55
0
        public async Task <string> GetAccessTokenAdal()
        {
            var creds = new Adal.ClientCredential(CLIENT_ID, CLIENT_SECRET);
            var ctx   = new Adal.AuthenticationContext($"https://login.microsoftonline.com/{TENANT_ID}", false);
            var token = await ctx.AcquireTokenAsync("https://database.windows.net/", creds);

            return(token.AccessToken);
        }
Exemple #56
0
        private async Task <string> GetTokenAsync()
        {
            var resourceID  = $"https://{config.Region}.asazure.windows.net";
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($"https://login.windows.net/{config.TenantId}");
            ClientCredential     credential = new ClientCredential(config.ClientId, config.ClientSecret);
            AuthenticationResult token      = await authContext.AcquireTokenAsync(resourceID, credential).ConfigureAwait(false);

            return(token.AccessToken); //Use this token to connect to AAS.
        }
Exemple #57
0
        private static async Task <Adalv2.AuthenticationResult> AcquireAadToken(string audience)
        {
            var authority   = GetAuthority(audience);
            var credential  = new Adalv2.ClientCredential(Config.InternalUsersClientId, Config.InternalUsersClientSecret);
            var authContext = new Adalv2.AuthenticationContext(authority);
            var result      = await authContext.AcquireTokenAsync(Config.InternalUsersClientId, credential);

            return(result);
        }
Exemple #58
0
        private string AcquireToken(string resourceURI, string authority, string clientId, string clientSecret, string redirectUrl, string userName)
        {
            var clientCredential = new ClientCredential(clientId, clientSecret);
            AuthenticationContext authContext =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false);
            AuthenticationResult result = authContext.AcquireTokenAsync(resourceURI, clientCredential).Result;

            return(result.AccessToken);
        }
        public async Task ForcePromptForSelectAccountPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"),
                                           // validate that authorizationUri passed to WebUi contains prompt=select_account query parameter
                                           new Dictionary <string, string> {
                { "prompt", "select_account" }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
                {
                    UserInfo =
                        new UserInfo()
                    {
                        DisplayableId = TestConstants.DefaultDisplayableId,
                        UniqueId      = TestConstants.DefaultUniqueId
                    }
                },
            },
                                                       TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                       new CallState(new Guid())).ConfigureAwait(false);

            ResetInstanceDiscovery();

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>
                {
                    { "grant_type", "authorization_code" }
                }
            });

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.SelectAccount)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Exemple #60
-2
        public void Run()
        {
            // Try to obtain the authorization token
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
            var result = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;

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

            // Read the token and create the appropriate credentials object
            string token = result.AccessToken;
            var credentials = new TokenCredentials(token);

            // Read the template and parameter file contents
            JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(credentials);
            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }