public static ClientAssertion CreateJwt(byte[] cert, string password, string issuer, string aud)
        {
            ClientAssertionCertificate certificate = new ClientAssertionCertificate(issuer, cert, password);

            JsonWebToken jwtToken = new JsonWebToken(certificate, aud);
            return jwtToken.Sign(certificate);
        }
        /// <summary>
        /// Creates a new instance of the <see cref="Tailspin.Surveys.Security.AdalCredential"/>
        /// </summary>
        /// <param name="clientAssertionCertificate">A <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate"/> instance containing an X509 certificate that identifies the client.</param>
        public AdalCredential(ClientAssertionCertificate clientAssertionCertificate)
        {
            Guard.ArgumentNotNull(clientAssertionCertificate, nameof(clientAssertionCertificate));

            ClientAssertionCertificate = clientAssertionCertificate;
            CredentialType = AdalCredentialType.ClientAssertionCertificate;
        }
        public static async Task ConfidentialClientWithX509TestAsync(Sts sts)
        {
            SetCredential(sts);
            var context = new AuthenticationContextProxy(sts.Authority, sts.ValidateAuthority, TokenCacheType.Null);

            string authorizationCode = await context.AcquireAccessCodeAsync(sts.ValidResource, sts.ValidConfidentialClientId, sts.ValidRedirectUriForConfidentialClient, sts.ValidUserId);
            var certificate = new ClientAssertionCertificate(sts.ValidConfidentialClientId, ExportX509Certificate(sts.ConfidentialClientCertificateName, sts.ConfidentialClientCertificatePassword), sts.ConfidentialClientCertificatePassword);
            RecorderJwtId.JwtIdIndex = 1;
            AuthenticationResultProxy result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate, null);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByAuthorizationCodeAsync(null, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "authorizationCode");

            result = await context.AcquireTokenByAuthorizationCodeAsync(string.Empty, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "authorizationCode");

            // Send null for redirect
            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, null, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "redirectUri");

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, (ClientAssertionCertificate)null, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "clientCertificate");
        }
        public static ClientAssertion CreateJwt(X509Certificate2 cert, string issuer, string aud)
        {
            ClientAssertionCertificate certificate = new ClientAssertionCertificate(issuer, cert);

            JsonWebToken jwtToken = new JsonWebToken(certificate, aud);
            return jwtToken.Sign(certificate);
        }
Пример #5
0
        public string GetX509CertificateThumbprint(ClientAssertionCertificate credential)
        {
            X509Certificate2 x509Certificate = new X509Certificate2(credential.Certificate, credential.Password);

            // Thumbprint should be url encoded
            return Base64UrlEncoder.Encode(x509Certificate.GetCertHash());            
        }
 private static async Task<string> GetAccessToken(X509Certificate2 certificate)
 {
     var authenticationContext = new AuthenticationContext(Authority, false);
     var cac = new ClientAssertionCertificate(ClientId, certificate);
     var authenticationResult = await authenticationContext.AcquireTokenAsync(GraphUrl, cac);
     return authenticationResult.AccessToken;
 }
 static KeyVaultAccessor()
 {
     keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));
     var clientAssertionCertPfx = CertificateHelper.FindCertificateByThumbprint(CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthCertThumbprintSetting));
     var client_id = CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthClientIdSetting);            
     assertionCert = new ClientAssertionCertificate(client_id, clientAssertionCertPfx);
 }
        //  The idea of the packages page is that it gets the list of packages from Lucene (from the Search Service)
        //  but when the owner is the current user (if there is a current user), packages owned by him are highlighted.
        //  So far this packages page just gets the list of registrations for which the current user is an owner.

        // GET: Packages
        public async Task<ActionResult> Index()
        {
            try
            {
                string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                string authority = string.Format(aadInstance, tenantId);
                AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserID));

                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                AuthenticationResult authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(signedInUserID, UserIdentifierType.UniqueId));

                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, nugetSearchServiceBaseAddress + "/query");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);

                HttpResponseMessage response;

                try
                {
                    response = await client.SendAsync(request);
                }
                catch (Exception e)
                {
                    return View("ServiceError", new ServiceErrorModel(e));
                }
                    
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    return View(new PackagesModel(JObject.Parse(json)));
                }
                else
                {
                    string err = await response.Content.ReadAsStringAsync();
                    return View("ServiceError", new ServiceErrorModel(response.StatusCode, err));
                }
            }
            catch (Exception)
            {
                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.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";

                return View();
            }
        }
Пример #9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            string ClientId = ConfigurationManager.AppSettings["ClientID"];
            string Authority = string.Format(ConfigurationManager.AppSettings["Authority"], ConfigurationManager.AppSettings["AADId"]);
            string AzureResourceManagerIdentifier = ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"];
                        
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions { });
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ClientId,
                    Authority = Authority,
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        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;
                            
                            object obj = null;
                            if (context.OwinContext.Environment.TryGetValue("DomainHint", out obj))
                            {
                                string domainHint = obj as string;
                                if (domainHint != null)
                                {
                                    context.ProtocolMessage.SetParameter("domain_hint", domainHint);
                                }
                            }

                            context.ProtocolMessage.RedirectUri = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                            context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action
                                ("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);
                            context.ProtocolMessage.Resource = AzureResourceManagerIdentifier;
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath
                                (ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet);
                            ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ClientId, keyCredential);

                            string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value
                                .Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

                            var tokenCache = new ADALTokenCache(signedInUserUniqueName);
                            tokenCache.Clear();

                            AuthenticationContext authContext = new AuthenticationContext(Authority, tokenCache);
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientAssertion);

                            return Task.FromResult(0);
                        }
                    }
                });
        }
Пример #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resource">https://longgod.sharepoint.com</param>
        /// <param name="tenantId"></param>
        /// <param name="clientId"></param>
        /// <param name="certificate"></param>
        /// <returns></returns>
        public static string GetAccessTokenByCertificateV2(string resource, string tenantId, string clientId, X509Certificate2 certificate)
        {
            string authority = string.Format("https://login.windows.net/{0}", tenantId);
            AuthenticationContext context = new AuthenticationContext(authority, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache.DefaultShared);
            var cac = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate(clientId.ToString(), certificate);

            return(context.AcquireTokenAsync(resource, cac).Result.AccessToken);
        }
Пример #11
0
        /// <summary>
        /// Authentication callback that gets a token using the X509 certificate
        /// </summary>
        /// <param name="authority">Address of the authority</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token</param>
        /// <param name="scope">Scope</param>
        /// <param name="assertionCert">The assertion certificate</param>
        /// <returns> The access token </returns>
        public static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert)
        {
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

            var result = await context.AcquireTokenAsync(resource, assertionCert);

            return result.AccessToken;
        }
        public async Task<ActionResult> Index()
        {
            try
            {
                var signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

                var userObjectIdClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                var userObjectId = userObjectIdClaim != null ? userObjectIdClaim.Value : signedInUserId;

                string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                string authority = string.Format(Startup.AuthorityFormat, tenantId);

                AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));

                AuthenticationResult authenticationResult;

                if (Startup.Certificate == null)
                {
                    ClientCredential credential = new ClientCredential(clientId, appKey);
                    authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, credential, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                }
                else
                {
                    ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                    authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                }

                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, nugetPublishServiceBaseAddress + "/domains");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    JArray result = JArray.Parse(json);

                    PublishModel model = new PublishModel();
                    foreach (string s in result.Values().Select(jtoken => jtoken.ToString()))
                    {
                        model.Domains.Add(s);
                    }

                    return View(model);
                }
                else
                {
                    return View(new PublishModel { Message = "Unable to load list of domains" });
                }
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                //TODO: this isn't quite right
                HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                return View(new PublishModel { Message = "AuthorizationRequired" });
            }
        }
        /// <summary>
        /// Authenticates the user silently using <see cref="AuthenticationContext.AcquireTokenSilentAsync(string, ClientAssertionCertificate, UserIdentifier)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientAssertionCertificate">The client assertion certificate of the application.</param>
        /// <param name="userIdentifier">The <see cref="UserIdentifier"/> of the user.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public async Task<IAuthenticationResult> AcquireTokenSilentAsync(
            string resource,
            ClientAssertionCertificate clientAssertionCertificate,
            UserIdentifier userIdentifier)
        {
            var result = await this.authenticationContext.AcquireTokenSilentAsync(resource, clientAssertionCertificate, userIdentifier);

            return result == null ? null : new AuthenticationResultWrapper(result);
        }
        public static List<Subscription> GetUserSubscriptions(string organizationId)
        {
            List<Subscription> subscriptions = null;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath
                    (ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet);
                ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], keyCredential);

                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));                
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"], clientAssertion,
                    new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                subscriptions = new List<Subscription>();

                // Get subscriptions to which the user has some kind of access
                string requestUrl = string.Format("{0}/subscriptions?api-version={1}", ConfigurationManager.AppSettings["AzureResourceManagerUrl"],
                    ConfigurationManager.AppSettings["AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Subscription Objects
                // id                                                  subscriptionId                       displayName state
                // --                                                  --------------                       ----------- -----
                // /subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e c276fc76-9cd4-44c9-99a7-4fd71546436e Production  Enabled
                // /subscriptions/e91d47c4-76f3-4271-a796-21b4ecfe3624 e91d47c4-76f3-4271-a796-21b4ecfe3624 Development Enabled

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    var subscriptionsResult = (Json.Decode(responseContent)).value;

                    foreach (var subscription in subscriptionsResult)
                        subscriptions.Add(new Subscription()
                        {
                            Id = subscription.subscriptionId,
                            DisplayName = subscription.displayName,
                        });
                }
            }
            catch { }

            return subscriptions;
        }
Пример #15
0
        public ClientAssertionCertificate GetClientAssertionCertificate()
        {
            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            certStore.Open(OpenFlags.ReadOnly);

            X509Certificate2 cert = certStore.Certificates.Find(X509FindType.FindByThumbprint, SettingsHelper.CertThumbprint, false)[0];

            ClientAssertionCertificate cac = new ClientAssertionCertificate(SettingsHelper.ClientId, cert);

            return cac;
        }
Пример #16
0
        public  string GetAccessTokenCert(string authority, string resource, string scope)
        {
            var clientId = _configuration["KeyVault:AuthClientId"];

            var context = new AuthenticationContext(authority, null);

            var assertionCert = new ClientAssertionCertificate(clientId, clientAssertionCertPfx);

            var result = context.AcquireToken(resource, assertionCert);

            return result.AccessToken;
        }
        /// <summary>
        /// Authentication callback that gets a token using the X509 certificate
        /// </summary>
        /// <param name="authority">Address of the authority</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token</param>
        /// <param name="scope">Scope</param>
        /// <returns></returns>
        public static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var client_id = CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthClientIdSetting);

            var context = new AuthenticationContext(authority, null);
            
            var assertionCert = new ClientAssertionCertificate(client_id, clientAssertionCertPfx);

            var result = await context.AcquireTokenAsync(resource, assertionCert);

            return result.AccessToken;
        }
        private async static Task doStuffInOffice365()
        {
            //set the authentication context
            //you can do multi-tenant app-only, but you cannot use /common for authority...must get tenant ID
            string authority = "https://login.windows.net/rzna.onmicrosoft.com/";
            AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

            //read the certificate private key from the executing location
            //NOTE: This is a hack...Azure Key Vault is best approach
            var certPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            certPath = certPath.Substring(0, certPath.LastIndexOf('\\')) + "\\O365AppOnly_private.pfx";
            var certfile = System.IO.File.OpenRead(certPath);
            var certificateBytes = new byte[certfile.Length];
            certfile.Read(certificateBytes, 0, (int)certfile.Length);
            var cert = new X509Certificate2(
                certificateBytes,
                PRIVATE_KEY_PASSWORD,
                X509KeyStorageFlags.Exportable |
                X509KeyStorageFlags.MachineKeySet |
                X509KeyStorageFlags.PersistKeySet); //switchest are important to work in webjob
            ClientAssertionCertificate cac = new ClientAssertionCertificate(CLIENT_ID, cert);

            //get the access token to SharePoint using the ClientAssertionCertificate
            Console.WriteLine("Getting app-only access token to SharePoint Online");
            var authenticationResult = await authenticationContext.AcquireTokenAsync("https://rzna.sharepoint.com/", cac);
            var token = authenticationResult.AccessToken;
            Console.WriteLine("App-only access token retreived");

            //perform a post using the app-only access token to add SharePoint list item in Attendee list
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

            //create the item payload for saving into SharePoint
            var itemPayload = new
            {
                __metadata = new { type = "SP.Data.SampleListItem" },
                Title = String.Format("Created at {0} {1} from app-only AAD token", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString())
            };

            //setup the client post
            HttpContent content = new StringContent(JsonConvert.SerializeObject(itemPayload));
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            Console.WriteLine("Posting ListItem to SharePoint Online");
            using (HttpResponseMessage response = await client.PostAsync("https://rzna.sharepoint.com/_api/web/Lists/getbytitle('Sample')/items", content))
            {
                if (!response.IsSuccessStatusCode)
                    Console.WriteLine("ERROR: SharePoint ListItem Creation Failed!");
                else
                    Console.WriteLine("SharePoint ListItem Created!");
            }
        }
Пример #19
0
        public ClientKey(ClientAssertionCertificate clientCertificate, Authenticator authenticator)
        {
            this.Authenticator = authenticator;

            if (clientCertificate == null)
            {
                throw new ArgumentNullException("clientCertificate");
            }

            this.Certificate = clientCertificate;
            this.ClientId = clientCertificate.ClientId;
            this.HasCredential = true;
        }
        /// <summary>
        /// Create an application token provider that can retrieve tokens for the given application from the given context, using the given audience 
        /// and certificate.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="context">The authentication context to use when retrieving tokens.</param>
        /// <param name="tokenAudience">The token audience to use when retrieving tokens.</param>
        /// <param name="certificate">The certificate associated with Active Directory application.</param>
        /// <param name="authenticationResult">The token details provided when authenticating with the client credentials.</param>
        public ApplicationTokenProvider(AuthenticationContext context, string tokenAudience, ClientAssertionCertificate certificate, AuthenticationResult authenticationResult)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            if (authenticationResult == null)
            {
                throw new ArgumentNullException("authenticationResult");
            }

            Initialize(context, tokenAudience, certificate.ClientId, 
                new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)),
                authenticationResult, authenticationResult.ExpiresOn);
        }
Пример #21
0
    public async Task<string> GetAppOnlyAccessToken(string resource, string tenantId)
    {
      string authority = SettingsHelper.AzureADAuthority;
      var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false);

      // get certificate & password
      string certFile = HttpContext.Current.Server.MapPath(SettingsHelper.CertPfxFilePath);
      string certPassword = SettingsHelper.CertPfxFilePassword;
      var cert = new X509Certificate2(certFile, certPassword, X509KeyStorageFlags.MachineKeySet);
      var clientAssertionCert = new ClientAssertionCertificate(SettingsHelper.ClientId, cert);
      
      // authenticate
      var authResult = await authContext.AcquireTokenAsync(resource, clientAssertionCert);

      return authResult.AccessToken;
    }
        async Task<ActionResult> Send(string action)
        {
            var signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectIdClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
            var userObjectId = userObjectIdClaim != null ? userObjectIdClaim.Value : signedInUserId;

            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            string authority = string.Format(Startup.AuthorityFormat, tenantId);

            AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));

            AuthenticationResult authenticationResult;

            if (Startup.Certificate == null)
            {
                ClientCredential credential = new ClientCredential(clientId, appKey);
                authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, credential, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            }
            else
            {
                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            }

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, nugetPublishServiceBaseAddress.TrimEnd('/') + "/tenant/" + action);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);

            HttpResponseMessage response = await client.SendAsync(request);

            string message = null;
            if (response.IsSuccessStatusCode)
            {
                message = "OK";
            }
            else
            {
                JObject publishServiceResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
                message = string.Format("ERROR: {0}", publishServiceResponse["error"].ToString());
            }

            return View(new TenantModel { Message = message });
        }
Пример #23
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var cerificateThumbprint = CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthCertThumbprintSetting);
            var authenticationClientId = CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthClientIdSetting);

            var certificate = CertificateHelper.FindCertificateByThumbprint(cerificateThumbprint);
            var assertionCert = new ClientAssertionCertificate(authenticationClientId, certificate);

            // initializes configuration manager with key vault authentication and the secret cache default timespan
            ConfigurationManager.Initialize(
                new KeyVaultClient.AuthenticationCallback(
                    (authority, resource, scope) => GetAccessToken(authority, resource, scope, assertionCert)), 
                Constants.KeyVaultSecretCacheDefaultTimeSpan);

            RoleEnvironment.Changed += RoleEnvironment_Changed;
        }
Пример #24
0
        private AuthenticationResult GetAppOnlyAccessToken(string tenantId, string resource)
        {
            var authority = _appConfig.AuthorizationUri.Replace("common", tenantId);
            var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(
                authority,
                false);

            var certfile = _appConfig.ClientCertificatePfx;

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

            var cac = new ClientAssertionCertificate(_appConfig.ClientId, cert);

            var authenticationResult = authenticationContext.AcquireToken(
                resource,
                cac);

            return authenticationResult;
        }
        public static async Task<Models.CachedAccessToken> GetAccessTokenAsync(string tenantId, string resource, bool useDogfood)
        {
            IAppConfig app = /*useDogfood ? new DogfoodAppConfig() :*/ new ProductionAppConfig();

            string authority = app.AuthorizationServiceUri.Replace("common", tenantId);
            AuthenticationContext authContext = new AuthenticationContext(authority, false);


            var certDataBase64 = ConfigurationManager.AppSettings["PrivateCertificateBase64"];
            var certBinaryData = Convert.FromBase64String(certDataBase64);
            var password = ConfigurationManager.AppSettings["CertificatePassword"];

            X509Certificate2 cert = new X509Certificate2(certBinaryData, password, X509KeyStorageFlags.MachineKeySet);

            var clientAppId = ConfigurationManager.AppSettings["ClientAppId"];

            ClientAssertionCertificate cac = new ClientAssertionCertificate(clientAppId, cert);

            var authenticationResult = await authContext.AcquireTokenAsync(resource, cac);
            return new Models.CachedAccessToken(authenticationResult.AccessToken, authenticationResult.ExpiresOn);
        }
Пример #26
0
        public ActionResult AppOnlyAccessToken()
        {
            string urlTokenEndpointForTenant =
                string.Format("https://login.windows.net/{0}/oauth2/token",
                              CustomAuthenticationManager.GetTenantID());

            ADAL.AuthenticationContext authenticationContext
                = new ADAL.AuthenticationContext(urlTokenEndpointForTenant);

            string resource = DemoConstants.TargetResource;

            ADAL.ClientAssertionCertificate clientAssertionCertificate =
                DemoConstants.GetClientAssertionCertificate();

            ADAL.AuthenticationResult authenticationResult =
                authenticationContext.AcquireToken(resource, clientAssertionCertificate);

            string           appOnlyAccessToken    = authenticationResult.AccessToken;
            JwtSecurityToken jwtAppOnlyAccessToken = new JwtSecurityToken(appOnlyAccessToken);

            return(View(jwtAppOnlyAccessToken));
        }
        public static async Task ConfidentialClientWithX509TestAsync(Sts sts)
        {
            SetCredential(sts);
            var context = new AuthenticationContextProxy(sts.Authority, sts.ValidateAuthority, TokenCacheType.Null);

            string authorizationCode = context.AcquireAccessCode(sts.ValidResource, sts.ValidConfidentialClientId, sts.ValidRedirectUriForConfidentialClient, sts.ValidUserId);
            var certificate = new ClientAssertionCertificate(sts.ValidConfidentialClientId, new X509Certificate2(sts.ConfidentialClientCertificateName, sts.ConfidentialClientCertificatePassword));
            RecorderJwtId.JwtIdIndex = 1;
            AuthenticationResultProxy result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, certificate, sts.ValidResource);
            VerifySuccessResult(sts, result, true, false);

            result = await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, sts.ValidConfidentialClientId, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidRequest, null, 400, "90014");   // The request body must contain the following parameter: 'client_secret or client_assertion'.

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, certificate, null);
            VerifySuccessResult(sts, result);

            result = await context.AcquireTokenByAuthorizationCodeAsync(null, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "authorizationCode");

            result = await context.AcquireTokenByAuthorizationCodeAsync(string.Empty, sts.ValidRedirectUriForConfidentialClient, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "authorizationCode");

            // Send null for redirect
            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, null, certificate, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "redirectUri");

            result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, sts.ValidRedirectUriForConfidentialClient, (ClientAssertionCertificate)null, sts.ValidResource);
            VerifyErrorResult(result, Sts.InvalidArgumentError, "clientCertificate");
        }
 public JWTHeader(ClientAssertionCertificate credential)
 {
     this.Credential = credential;
 }
Пример #29
0
        static void Main(string[] args)
        {

            KeyBundle keyBundle = null; // The key specification and attributes
            Secret secret = null;
            string keyName = string.Empty;
            string secretName = string.Empty;

            inputValidator = new InputValidator(args);

            TracingAdapter.AddTracingInterceptor(new ConsoleTracingInterceptor());
            TracingAdapter.IsEnabled = inputValidator.GetTracingEnabled();

            var clientId = ConfigurationManager.AppSettings["AuthClientId"];

            var cerificateThumbprint = ConfigurationManager.AppSettings["AuthCertThumbprint"];

            var certificate = FindCertificateByThumbprint(cerificateThumbprint);
            var assertionCert = new ClientAssertionCertificate(clientId, certificate);

            keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback( 
                   (authority, resource, scope) => GetAccessToken(authority, resource, scope, assertionCert)), 
                   GetHttpClient());

            // SECURITY: DO NOT USE IN PRODUCTION CODE; FOR TEST PURPOSES ONLY
            //ServicePointManager.ServerCertificateValidationCallback += ( sender, cert, chain, sslPolicyErrors ) => true;

            List<KeyOperationType> successfulOperations = new List<KeyOperationType>();
            List<KeyOperationType> failedOperations = new List<KeyOperationType>();

            foreach (var operation in inputValidator.GetKeyOperations())
            {
                try
                {
                    Console.Out.WriteLine(string.Format("\n\n {0} is in process ...", operation.ToString()));
                    switch (operation)
                    {
                        case KeyOperationType.CREATE_KEY:
                            keyBundle = CreateKey(keyBundle, out keyName);
                            break;

                        case KeyOperationType.IMPORT_KEY:
                            keyBundle = ImportKey(out keyName);
                            break;

                        case KeyOperationType.GET_KEY:
                            keyBundle = GetKey(keyBundle);
                            break;

                        case KeyOperationType.LIST_KEYVERSIONS:
                            ListKeyVersions(keyName);
                            break;

                        case KeyOperationType.UPDATE_KEY:
                            keyBundle = UpdateKey(keyName);
                            break;

                        case KeyOperationType.DELETE_KEY:
                            DeleteKey(keyName);
                            break;

                        case KeyOperationType.BACKUP_RESTORE:
                            keyBundle = BackupRestoreKey(keyName);
                            break;

                        case KeyOperationType.SIGN_VERIFY:
                            SignVerify(keyBundle);
                            break;

                        case KeyOperationType.ENCRYPT_DECRYPT:
                            EncryptDecrypt(keyBundle);
                            break;

                        case KeyOperationType.ENCRYPT:
                            Encrypt(keyBundle);
                            break;

                        case KeyOperationType.DECRYPT:
                            Decrypt(keyBundle);
                            break;

                        case KeyOperationType.WRAP_UNWRAP:
                            WrapUnwrap(keyBundle);
                            break;

                        case KeyOperationType.CREATE_SECRET:
                            secret = CreateSecret(out secretName);
                            break;

                        case KeyOperationType.GET_SECRET:
                            secret = GetSecret(secret.Id);
                            break;

                        case KeyOperationType.LIST_SECRETS:
                            ListSecrets();
                            break;

                        case KeyOperationType.DELETE_SECRET:
                            secret = DeleteSecret(secretName);
                            break;
                    }
                    successfulOperations.Add(operation);
                }
                catch (KeyVaultClientException exception)
                {
                    // The Key Vault exceptions are logged but not thrown to avoid blocking execution for other commands running in batch
                    Console.Out.WriteLine("Operation failed: {0}", exception.Message);
                    failedOperations.Add(operation);
                }

            }

            Console.Out.WriteLine("\n\n---------------Successful Key Vault operations:---------------");
            foreach (KeyOperationType type in successfulOperations)
                Console.Out.WriteLine("\t{0}", type);

            if (failedOperations.Count > 0)
            {
                Console.Out.WriteLine("\n\n---------------Failed Key Vault operations:---------------");
                foreach (KeyOperationType type in failedOperations)
                    Console.Out.WriteLine("\t{0}", type);
            }

            Console.Out.WriteLine();
            Console.Out.Write("Press enter to continue . . .");
            Console.In.Read();
        }
 public JWTHeaderWithCertificate(ClientAssertionCertificate credential)
     : base(credential)
 {
 }
Пример #31
0
        public void ConfigureAuth(IAppBuilder app)
        {
            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;

                            if ( certName.Length != 0)
                            {
                                // Create a Client Credential Using a Certificate
                                //
                                // Initialize the Certificate Credential to be used by ADAL.
                                // First find the matching certificate in the cert store.
                                //

                                X509Certificate2 cert = null;
                                X509Store store = new X509Store(StoreLocation.CurrentUser);
                                try
                                {
                                    store.Open(OpenFlags.ReadOnly);
                                    // Place all certificates in an X509Certificate2Collection object.
                                    X509Certificate2Collection certCollection = store.Certificates;
                                    // Find unexpired certificates.
                                    X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                                    // From the collection of unexpired certificates, find the ones with the correct name.
                                    X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
                                    if (signingCert.Count == 0)
                                    {
                                        // No matching certificate found.
                                        return Task.FromResult(0);
                                    }
                                    // Return the first certificate in the collection, has the right name and is current.
                                    cert = signingCert[0];
                                }
                                finally
                                {
                                    store.Close();
                                }

                                // Then create the certificate credential.
                                ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert);

                                string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                                    "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                                AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                                AuthenticationHelper.token = result.AccessToken;
                            }
                            else
                            {
                                // Create a Client Credential Using an Application Key
                                ClientCredential credential = new ClientCredential(clientId, appKey);
                                string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                                    "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                                AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                                AuthenticationHelper.token = result.AccessToken;
                            }

                            return Task.FromResult(0);
                        }

                    }

                });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            Certificate = LoadCertificate();

            if (Certificate == null)
            {
                throw new Exception("Certificate == null");
            }

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

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

                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        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 = async (context) =>
                        {
                            //  This code gets the AccessToken for the AAD graph. This will be needed for some scenarios. However, it might 
                            //  be that we should ask for the services resource id at this stage. The AuthenticationResult includes a RefreshToken.
                            
                            var code = context.Code;

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

                            string authority = string.Format(aadInstance, tenantId);

                            AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));
                            ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Certificate);
                            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientAssertionCertificate, graphResourceId);
                        },
                        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);
                        },
                        SecurityTokenReceived = (context) =>
                        {
                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            //context.OwinContext.Response.Redirect("/Home/Error");
                            //context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });
        }
        private static string EncodeHeaderToJson(ClientAssertionCertificate credential)
        {
            JWTHeaderWithCertificate header = new JWTHeaderWithCertificate(credential);

            return(EncodeToJson(header));
        }
  /// <summary>
  /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential.
  /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
  /// for detailed instructions on creating an Azure Active Directory application.
  /// </summary>
  /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
  /// <param name="certificate">The certificate associated with Active Directory application.</param>
  /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
  /// <param name="cache">The token cache to target during authentication.</param>
  /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, ClientAssertionCertificate certificate,
      ActiveDirectoryServiceSettings settings, TokenCache cache)
  {
      return await LoginSilentAsync(domain, certificate.ClientId, 
          new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)), settings, cache);
  }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential. Uses the default token cache for authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentWithCertificateAsync(string domain, ClientAssertionCertificate certificate,
     ActiveDirectoryServiceSettings settings)
 {
     return await LoginSilentAsync(domain, certificate, settings, TokenCache.DefaultShared);
 }
 public string GetX509CertificateThumbprint(ClientAssertionCertificate credential)
 {
     throw new NotImplementedException();
 }