示例#1
0
        public static AuthenticationResult GetGraphClientByUserAndPassword(string Tenant, string ClientId, string RedirectURI, string Resource, string User, SecureString Password)
        {
            string authority             = "https://login.microsoftonline.com/" + Tenant;
            var    authenticationContext = new AuthenticationContext(authority);
            AuthenticationResult AuthenticationResult;
            IntPtr valuePtr = IntPtr.Zero;

            valuePtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
            string strPassword = Marshal.PtrToStringUni(valuePtr);

            Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
            var aadCredential = new UserPasswordCredential(User, strPassword);

            try
            {
                var taskResult = authenticationContext.AcquireTokenAsync(Resource, ClientId, aadCredential);
                AuthenticationResult = taskResult.GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The user or administrator has not consented to use the application"))
                {
                    var tempURI    = new Uri(RedirectURI);
                    var taskResult = authenticationContext.AcquireTokenAsync(Resource, ClientId, tempURI, new PlatformParameters(PromptBehavior.Always));
                    AuthenticationResult = taskResult.GetAwaiter().GetResult();
                }
                else
                {
                    throw ex;
                }
            }
            return(AuthenticationResult);
        }
示例#2
0
        public async Task <IHttpActionResult> Get([FromUri] bool includeTokens = false)
        {
            // Create a user password cradentials.
            var credential = new UserPasswordCredential(Username, Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(AuthorityUrl);
            var authenticationResult  = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

            using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

                var reportsWithTokens = reports.Value
                                        .Select(report =>
                {
                    string accessToken = null;
                    if (includeTokens)
                    {
                        // Generate Embed Token for reports without effective identities.
                        GenerateTokenRequest generateTokenRequestParameters;
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                        var tokenResponse = client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters).Result;
                        accessToken       = tokenResponse.Token;
                    }

                    return(new ReportWithToken(report, accessToken));
                }).ToList();

                return(Ok(reportsWithTokens));
            }
        }
示例#3
0
        private async void Window_Loaded()
        {
            string authority = aadInstance;

            TokenCache TC = new TokenCache();

            var authContext = new AuthenticationContext(authority, TC);
            var c           = new UserPasswordCredential(UserId, Password);

            var result = await authContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api", ClientId, c);

            token = result.AccessToken;

            var tokenCredentials = new TokenCredentials(token, "Bearer");


            using (var client = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials))
            {
                var b = client.Reports.GetReportInGroup(GroupId, ReportId);

                var embedUrl = b.EmbedUrl;
                webBrowser1.Navigate(embedUrl);

                webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
            }
        }
        protected static void AcquireAccessToken()
        {
            Console.WriteLine("Calling to acquire access token...");

            // create new ADAL authentication context
            var authenticationContext =
                new AuthenticationContext(ProgramConstants.AzureAuthorizationEndpoint);

            // To Enforce the TLS 1.2 Protocol
            ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;

            // use authentication context to trigger user sign-in and return access token
            var userCreds = new UserPasswordCredential("*****@*****.**", "myEasyToCrackPassword");

            var userAuthnResult = authenticationContext.AcquireTokenAsync(ProgramConstants.PowerBiServiceResourceUri,
                                                                          ProgramConstants.ClientID,
                                                                          userCreds).Result;


            // cache access token in AccessToken field
            AccessToken = userAuthnResult.AccessToken;

            Console.WriteLine(" - access token successfully acquired");
            Console.WriteLine();
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var credential = new UserPasswordCredential(Username, Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(AuthorityUrl);
            var authenticationResult  = authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential).Result;

            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

            // Create a Power BI Client object (it will be used to call Power BI APIs)
            using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
            {
                // Get a list of reports
                var reports = client.Reports.GetReportsInGroup(GroupId);

                // Get the first report in the group
                var report = reports.Value.FirstOrDefault();

                // Generate an embed token
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = client.Reports.GenerateTokenInGroup(GroupId, report.Id, generateTokenRequestParameters);

                embedToken = tokenResponse.Token;
                embedUrl   = report.EmbedUrl;
                reportId   = report.Id;
            }
        }
示例#6
0
        static public string AquireAADToken(string resourceId = "")
        {
            if (string.IsNullOrEmpty(resourceId))
            {
                resourceId = sfbResourceId;
            }
            else
            {
                resourceId = new Uri(resourceId).Scheme + "://" + new Uri(resourceId).Host;
            }

            var authContext = new AuthenticationContext(string.Format(aadInstance, tenant));

            var cred = new UserPasswordCredential(username, password);
            AuthenticationResult authenticationResult = null;

            try
            {
                authenticationResult = authContext.AcquireTokenAsync(resourceId, clientId, cred).Result;
            }
            catch (Exception ex)
            {
            }

            return(authenticationResult.AccessToken);
        }
示例#7
0
        public async Task <string> GenerateBearerTokenByPricipalUserCredentials(string resoureUrl)
        {
            if (string.IsNullOrEmpty(resoureUrl))
            {
                return(null);
            }

            try
            {
                var authContext = new AuthenticationContext(this.autorityUrl);

                var userAuth = new UserPasswordCredential(
                    ConfigurationManager.configurationSettings[ConfigurationKeys.UserKeys.UserName],
                    ConfigurationManager.configurationSettings[ConfigurationKeys.UserKeys.Password]);

                var authenticationResult = await authContext.AcquireTokenAsync(
                    resoureUrl,
                    this.clientId,
                    userAuth).ConfigureAwait(false);

                return(authenticationResult.AccessToken);
            }
            catch (AdalException ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
示例#8
0
        private string GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.microsoftonline.com/common/";

            //Get access token:
            // To call a Power BI 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.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            var userCredential = new UserPasswordCredential(Sitecore.Configuration.Settings.GetSetting("PowerBIUserEmail"), Sitecore.Configuration.Settings.GetSetting("PowerBIUserPassword"));

            Task <AuthenticationResult> task = authContext.AcquireTokenAsync(resourceUri, clientID, userCredential);

            task.Wait();

            string token = task.Result.AccessToken;

            Console.WriteLine(token);
            Console.ReadLine();

            return(token);
        }
        public async Task <EmbedConfig> EmbedReport()
        {
            var Username = "******";
            var Password = "******";
            // Create a user password cradentials.
            var credential = new UserPasswordCredential(Username, Password);

            //Authenticate On Azure.
            var AuthorityUrl          = "https://login.windows.net/common/oauth2/authorize/";
            var ResourceUrl           = "https://analysis.windows.net/powerbi/api";
            var ClientId              = "YOUR CLIENT ID HERE";
            var authenticationContext = new AuthenticationContext(AuthorityUrl);
            var authenticationResult  = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

            //GetToken If Authenticated
            if (authenticationResult == null)
            {
                return(null);
            }
            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");


            var ApiUrl = "https://api.powerbi.com/";

            using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var GroupId = "GROUP ID";
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

                // Get the related report in the group.
                var ReportId = "REPORT ID";
                var report   = reports.Value.Where(k => k.Id == ReportId).FirstOrDefault();

                if (report == null)
                {
                    return(null);
                }

                // Generate Embed Token.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);

                if (tokenResponse == null)
                {
                    return(null);
                }

                var Tokken = tokenResponse.Token;
                // Generate Embed Configuration. These properties (EmbedToken, EmbedUrl, Id) could be used on fronthand to embed powerbi report
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse.Token,
                    EmbedUrl   = report.EmbedUrl,
                    Id         = report.Id
                };

                return(embedConfig);
            }
        }
        public Token GetTokenAccess()
        {
            try
            {
                AuthorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
                ResourceUrl  = ConfigurationManager.AppSettings["resourceUrl"];
                ApiUrl       = ConfigurationManager.AppSettings["apiUrl"];
                Username     = ConfigurationManager.AppSettings["username"];

                Credential = new UserPasswordCredential(Username, Secrets.Password);
                Authorize().Wait();

                using (var client = new PowerBIClient(new Uri(ApiUrl), TokenCredentials))
                {
                    EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId: GroupId, reportKey: ReportId, requestParameters: new GenerateTokenRequest(accessLevel: AccessLevel, datasetId: DatasetId));
                    Report     report     = client.Reports.GetReportInGroup(groupId: GroupId, reportKey: ReportId);

                    return(new Token {
                        EmbedUrl = report.EmbedUrl, EmbedToken = embedToken, Id = embedToken.TokenId
                    });
                }
            }
            catch (Exception ex)
            {
                return(new Token {
                    ErrorMessage = ex.InnerException.ToString()
                });
            }
        }
        public JwtAuthProviderReaderTests()
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidationCallback);

            var publicKeys   = AzureADAuthProviderReader.RetrievePublicKeys(AzureADSettings.Tenant);
            var publicKeyXml = publicKeys.First().ToPublicKeyXml();

            clientCredential = new ClientCredential(
                AzureADSettings.TodoListDemo_ClientId,
                AzureADSettings.TodoListDemo_ClientSecret);

            userCredential = new UserPasswordCredential(
                AzureADSettings.User1_UserName,
                AzureADSettings.User1_Password);

            _tokenHelper = new TokenHelper(AzureADSettings.Audience, AzureADSettings.Tenant);

            appHost = new JwtAuthProviderReaderAppHost
            {
                AppSettings = new DictionarySettings(new Dictionary <string, string> {
                    { "jwt.HashAlgorithm", "RS256" },
                    { "jwt.PublicKeyXml", publicKeyXml },
                    { "jwt.RequireSecureConnection", "False" },
                    { "jwt.Audience", AzureADSettings.Audience },
                })
            }
            .Init()
            .Start("http://*:2337/");
        }
        public AzureADAuthProviderReaderTests()
        {
            ServicePointManager.ServerCertificateValidationCallback
                = new RemoteCertificateValidationCallback(OnValidationCallback);

            clientCredential = new ClientCredential(
                AzureADSettings.TodoListDemo_ClientId,
                AzureADSettings.TodoListDemo_ClientSecret);

            userCredential = new UserPasswordCredential(
                AzureADSettings.User1_UserName,
                AzureADSettings.User1_Password);

            _tokenHelper = new TokenHelper(audience, tenant);

            appHost = new AzureADAuthProviderReaderAppHost
            {
                AppSettings = new DictionarySettings(new Dictionary <string, string> {
                    { "aadr.RequireSecureConnection", "False" },
                    { "aadr.Audience", audience },
                    { "aadr.Tenant", tenant },
                })
            }
            .Init()
            .Start("http://*:2337/");
        }
        public static async Task <string> AcquireToken(Dictionary <string, string> input)
        {
            Dictionary <string, object> res = new Dictionary <string, object>();
            AuthenticationContext       ctx = new AuthenticationContext(input["authority"]);

            try
            {
                AuthenticationResult result = null;

                if (!input.ContainsKey("redirect_uri"))
                {
                    UserCredential userCred = new UserCredential();
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], userCred).ConfigureAwait(false);
                }
                else if (input.ContainsKey("user_identifier") && input.ContainsKey("password"))
                {
                    UserPasswordCredential user = new UserPasswordCredential(input["user_identifier"], input["password"]);
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], user).ConfigureAwait(false);
                }
                else
                {
                    string prompt = input.ContainsKey("prompt_behavior") ? input["prompt_behavior"] : null;
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]),
                                                         GetPlatformParametersInstance(prompt)).ConfigureAwait(false);
                }
                res = ProcessResult(result, input);
            }
            catch (Exception exc)
            {
                res.Add("error", exc.Message);
            }
            return(FromDictionaryToJson(res));
        }
示例#14
0
        /// <summary>
        /// Retrieves an authentication header from the service.
        /// </summary>
        /// <returns>The authentication header for the Web API call.</returns>
        public static string GetAuthenticationHeader(bool useWebAppAuthentication = false)
        {
            string aadTenant          = ClientConfiguration.Default.ActiveDirectoryTenant;
            string aadClientAppId     = ClientConfiguration.Default.ActiveDirectoryClientAppId;
            string aadClientAppSecret = ClientConfiguration.Default.ActiveDirectoryClientAppSecret;
            string aadResource        = ClientConfiguration.Default.ActiveDirectoryResource;

            AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant, false);
            AuthenticationResult  authenticationResult;

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            if (useWebAppAuthentication)
            {
                if (string.IsNullOrEmpty(aadClientAppSecret))
                {
                    Console.WriteLine("Please fill AAD application secret in ClientConfiguration if you choose authentication by the application.");
                    throw new Exception("Failed OAuth by empty application secret.");
                }

                try
                {
                    // OAuth through application by application id and application secret.
                    var creadential = new ClientCredential(aadClientAppId, aadClientAppSecret);
                    authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Failed to authenticate with AAD by application with exception {0} and the stack trace {1}", ex.ToString(), ex.StackTrace));
                    throw new Exception("Failed to authenticate with AAD by application.");
                }
            }
            else
            {
                // OAuth through username and password.
                string username = ClientConfiguration.Default.UserName;
                string password = ClientConfiguration.Default.Password;

                if (string.IsNullOrEmpty(password))
                {
                    Console.WriteLine("Please fill user password in ClientConfiguration if you choose authentication by the credential.");
                    throw new Exception("Failed OAuth by empty password.");
                }

                try
                {
                    // Get token object
                    var userCredential = new UserPasswordCredential(username, password);;
                    authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, aadClientAppId, userCredential).Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Failed to authenticate with AAD by the credential with exception {0} and the stack trace {1}", ex.ToString(), ex.StackTrace));
                    throw new Exception("Failed to authenticate with AAD by the credential.");
                }
            }

            // Create and get JWT token
            return(authenticationResult.CreateAuthorizationHeader());
        }
示例#15
0
        public async Task <IHttpActionResult> Get(string id)
        {
            // Create a user password cradentials.
            var credential = new UserPasswordCredential(Username, Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(AuthorityUrl);
            var authenticationResult  = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

            using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

                var report = reports.Value.FirstOrDefault(r => r.Id == id);

                // Generate Embed Token for reports without effective identities.
                GenerateTokenRequest generateTokenRequestParameters;
                generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);

                var reportWithToken = new ReportWithToken(report, tokenResponse.Token);

                return(Ok(reportWithToken));
            }
        }
示例#16
0
        private async Task <AuthenticationResult> DoAuthentication()
        {
            AuthenticationResult authenticationResult = null;

            if (AuthenticationType.Equals("MasterUser"))
            {
                var authenticationContext = new AuthenticationContext(AuthorityUrl);

                // Authentication using master user credentials
                var credential = new UserPasswordCredential(Username, Password);
                authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential).Result;
            }
            else
            {
                // For app only authentication, we need the specific tenant id in the authority url
                var tenantSpecificURL     = AuthorityUrl.Replace("common", Tenant);
                var authenticationContext = new AuthenticationContext(tenantSpecificURL);

                // Authentication using app credentials
                var credential = new ClientCredential(ApplicationId, ApplicationSecret);
                authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, credential);
            }

            return(authenticationResult);
        }
        // GET api/values
        public async Task <string> Get(string ClientId, string username, string password)
        {
            string clientId = "9cf11af2-b7dd-4081-af7f-98f3d34b4737";

            List <string> lst         = new List <string>();
            var           credentials = new UserPasswordCredential("", "");
            var           authContext = new AuthenticationContext("https://login.microsoftonline.com/414e96d3-f8a4-4c10-b323-11fa8ebfe195/oauth2/token"); //https://login.microsoftonline.com/414e96d3-f8a4-4c10-b323-11fa8ebfe195/oauth2/token
                                                                                                                                                          //var authContext = new AuthenticationContext("https://login.microsoftonline.com/common/oauth2/authorize");


            var authResult = await authContext.AcquireTokenAsync("https://managment.azure.com/", clientId, credentials);

            if (authResult == null)
            {
                lst.Add("Error");
                // return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Code or Member Not Found");
            }

            return(null);

            //var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
            //var azure = Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionID);
            //var resourecelist = azure.ResourceGroups.List().ToList();

            //var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
            //var resourceClient = new ResourceManagementClient(serviceCreds);
            //resourceClient.SubscriptionId = subscriptionID;
        }
        // Calls user resource URI to get the applications resource URI
        private async Task <Uri> UcwaUserDiscovery(Uri userDiscoverUri, int redirectionCount = 0)
        {
            if (redirectionCount > ucwaMaxRedirection)
            {
                throw CreateAPIError("3", "Maximum redirection count exceeded during user autodiscovery.");
            }
            var    pwdCred     = new UserPasswordCredential(username, password);
            string resource    = userDiscoverUri.GetLeftPart(System.UriPartial.Authority);
            string accessToken = await this.GetAADToken(authorityUri, clientId, pwdCred, resource);

            var     request  = this.CreateUCWARequest(userDiscoverUri.ToString(), "GET", accessToken);
            var     response = this.GetResponse(request);
            dynamic tmp      = JsonConvert.DeserializeObject(response);

            try
            {
                // redirect doesn't include /oauth/user for whatever reason
                var redirectUri = new Uri(tmp._links.redirect.href.ToString() + "/oauth/user");
                return(await UcwaUserDiscovery(redirectUri, redirectionCount + 1));
            }
            catch
            {
                string applicationsResource = tmp._links.applications.href;
                return(new Uri(applicationsResource));
            }
        }
示例#19
0
        public async Task <string> AuthenticatePowerBIUser(LoginModel loginModel)
        {
            try
            {
                //The client id that Azure AD created when you registered your client app.
                string clientID = System.Configuration.ConfigurationManager.AppSettings["powerBIClientId"];

                //RedirectUri you used when you register your app.
                //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
                // You can use this redirect uri for your client app
                //string redirectUri = "urn:ietf:wg:oauth:2.0:oob";

                //Resource Uri for Power BI API
                string resourceUri = System.Configuration.ConfigurationManager.AppSettings["powerBIresourceUri"];

                //OAuth2 authority Uri
                string authorityUri = System.Configuration.ConfigurationManager.AppSettings["powerBIauthorityUri"];

                string username = loginModel.UserName;
                string password = loginModel.Password;
                //Get access token:
                // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
                // AcquireToken will acquire an Azure access token
                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                AuthenticationContext authContext = new AuthenticationContext(authorityUri);
                var credential = new UserPasswordCredential(username, password);
                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult res = authContext.AcquireTokenAsync(resourceUri, clientID, credential).Result;

                return(res.AccessToken);
            }
            catch (Exception ex)
            {
                return("PowerBI Authentication failed");
            }
        }
示例#20
0
        public async static Task <string> GetPowerBIAPIAuthTokenAsync()
        {
            string authorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
            string resourceUrl  = ConfigurationManager.AppSettings["powerbiresourceUrl"];

            string clientId     = ConfigurationManager.AppSettings["client_id"];
            string clientSecret = ConfigurationManager.AppSettings["client_secret"];

            string userid   = ConfigurationManager.AppSettings["powerbi_user"];
            string password = ConfigurationManager.AppSettings["powerbi_password"];


            // Create a user password cradentials.
            var credential = new UserPasswordCredential(userid, password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(authorityUrl);
            var authenticationResult  = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);

            if (authenticationResult == null)
            {
                throw new Exception("Authentication Failed");
            }

            return(authenticationResult.AccessToken);
        }
示例#21
0
        static string GetAccessToken()
        {
            AuthenticationContext authContext = new AuthenticationContext(aadAuthorizationEndpoint);
            var userCredentials = new UserPasswordCredential(pbiUserName, pbiUserPassword);

            return(authContext.AcquireTokenAsync(resourceUriPowerBi, clientId, userCredentials).Result.AccessToken);
        }
示例#22
0
        /// <summary>
        /// Retrieves an authentication header from the service.
        /// </summary>
        /// <returns>The authentication header for the Web API call.</returns>
        public static string GetAuthenticationHeader(ClientConfiguration clientConfig, bool useWebAppAuthentication = false)
        {
            string aadTenant      = clientConfig.ActiveDirectoryTenant;
            string aadClientAppId = clientConfig.ActiveDirectoryClientAppId;
            string aadResource    = clientConfig.ActiveDirectoryResource;

            AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
            AuthenticationResult  authenticationResult;

            if (useWebAppAuthentication)
            {
                string aadClientAppSecret = clientConfig.ActiveDirectoryClientAppSecret;
                var    creadential        = new ClientCredential(aadClientAppId, aadClientAppSecret);
                authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
            }
            else
            {
                // OAuth through username and password.
                string username = clientConfig.UserName;
                string password = clientConfig.Password;

                // Get token object
                var userCredential = new UserPasswordCredential(username, password);
                authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, aadClientAppId, userCredential).Result;
                //authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, aadClientAppId, new System.Uri(aadTenant), new PlatformParameters(PromptBehavior.RefreshSession, false)).Result;
            }

            // Create and get JWT token
            return(authenticationResult.CreateAuthorizationHeader());
        }
示例#23
0
        internal static async void GetToken(string userId, string password)
        {
            // Get the Resource Url & Authority Url using the Api method. This is the best way to get authority URL
            // for any Azure service api.
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;

            string resourceUrl  = ap.Resource;
            string authorityUrl = ap.Authority;

            //Generate the Authority context .. For the sake of simplicity for the post, I haven't splitted these
            // in to multiple methods. Ideally, you would want to use some sort of design pattern to generate the context and store
            // till the end of the program.
            authContext = new AuthenticationContext(authorityUrl, false);

            // UserCrendetial object will only accept User Id
            //          starting from the latest version of .NET
            // Thats the reason why we are using UserPasswordCredential
            //         object which is actually inherited by UserCredential.
            UserCredential credentials = new UserPasswordCredential(userId, password);

            //Genertae the AuthToken by using Credentials object.
            authToken = await authContext.AcquireTokenAsync
                            (resourceUrl, clientId, credentials);

            WriteLine("Got the authentication token, Getting data from Webapi !!");

            GetData(authToken.AccessToken);
        }
示例#24
0
        /// <summary>
        /// Sets authorization header.
        /// </summary>
        /// <returns>Authorization header</returns>
        private async Task <string> AuthorizationHeader()
        {
            if (!string.IsNullOrEmpty(_authorizationHeader) &&
                (DateTime.UtcNow.AddSeconds(60) < AuthenticationResult.ExpiresOn))
            {
                return(_authorizationHeader);
            }

            var uri = new UriBuilder(_settings.AzureAuthEndpoint)
            {
                Path = _settings.AadTenant
            };

            var authenticationContext = new AuthenticationContext(uri.ToString());

            if (_settings.UseServiceAuthentication)
            {
                var credentials = new ClientCredential(_settings.AadClientId.ToString(), _settings.AadClientSecret);

                AuthenticationResult = await authenticationContext.AcquireTokenAsync(_settings.AosUri, credentials);
            }
            else
            {
                var credentials = new UserPasswordCredential(_settings.UserName, _settings.UserPassword);

                AuthenticationResult = await authenticationContext.AcquireTokenAsync(_settings.AosUri, _settings.AadClientId.ToString(), credentials);
            }

            return(_authorizationHeader = AuthenticationResult.CreateAuthorizationHeader());
        }
示例#25
0
        static void Main(string[] args)
        {
            var dt = new DateTime(1498464308079);

            authenticationContext = new AuthenticationContext
                                        (String.Format(CultureInfo.InvariantCulture, aadInstance, tenant));
            authenticationContext.TokenCache.Clear();
            AuthenticationResult testCredentials = null;
            UserCredential       uc = null;

            uc = new UserPasswordCredential(hardcodedUsername, hardcodedPassword);
            testCredentials     = GetAzureAdToken(authenticationContext, sfboResourceAppId, clientId, redirectUri, uc);
            Accesstoken         = testCredentials.AccessToken;
            ucwaApplicationsUri = GetUcwaRootUri(authenticationContext, sfboResourceAppId, clientId, redirectUri, uc);

            ucwaApplicationsHost     = ReduceUriToProtoAndHost(ucwaApplicationsUri);
            ucwaAuthenticationResult = GetAzureAdToken(authenticationContext, ucwaApplicationsHost, clientId, redirectUri, uc);
            Accesstoken = ucwaAuthenticationResult.AccessToken;

            UcwaMyAppsObject ucwaMyAppsObject = new UcwaMyAppsObject()
            {
                UserAgent  = "Notification_App",
                EndpointId = Guid.NewGuid().ToString(),
                Culture    = "en-US"
            };

            Console.WriteLine("Making request to ucwaApplicationsUri " + ucwaApplicationsUri);
            createUcwaAppsResults = CreateUcwaApps(ucwaAuthenticationResult, ucwaApplicationsUri, ucwaMyAppsObject);

            SendIMToUser(); // send im to user
        }
示例#26
0
        public AzureDataCatalog()
        {
            //NOTE: You must fill in the App.Config with the following three settings. The first two are values that you received registered your application with AAD. The 3rd setting is always the same value.:
            //< ADCImportExport.Properties.Settings >
            //    <setting name = "ClientId" serializeAs = "String">
            //           <value></value>
            //       </setting>
            //       <setting name = "RedirectURI" serializeAs = "String">
            //              <value> https://login.live.com/oauth20_desktop.srf</value>
            //    </setting>
            //    <setting name = "ResourceId" serializeAs = "String">
            //           <value> https://datacatalog.azure.com</value>
            //    </setting>
            //</ADCImportExport.Properties.Settings>

            var credential = new UserPasswordCredential(Username, Password);


            ClientId = "7b55229b-785b-4bc8-a3e3-6dad9728bd94";
            //RedirectUri = new Uri(ADCImportExport.Properties.Settings.Default.RedirectURI);

            CatalogName = "DefaultCatalog";

            var authContext = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize");

            authResult = authContext.AcquireTokenAsync(ResourceUrl, ClientId, credential).Result;

            var tokenCredentials = new TokenCredentials(authResult.AccessToken, "Bearer");
        }
        public static void Main(string[] args)
        {
            var username         = "******";       // This is your AAD username in the form [email protected].
            var password         = "******";       // This is your AAD password.
            var aadApplicationID = "[your AAD application ID]"; // Created when you register an AAD application: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications.

            var adalCredential = new UserPasswordCredential(username, password);

            var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common");
            var result = authenticationContext.AcquireTokenAsync(VstsResourceId, aadApplicationID, adalCredential).Result;

            var token          = new VssAadToken(result);
            var vstsCredential = new VssAadCredential(token);

            var connection = new VssConnection(new Uri("https://[your VSTS account name].visualstudio.com"), vstsCredential);
            var client     = connection.GetClient <DelegatedAuthorizationHttpClient>();

            var pat = client.CreateSessionToken(
                displayName: "Generated by sample code",
                tokenType: SessionTokenType.Compact,
                scope: "vso.work"
                ).Result;

            Console.WriteLine(pat.Token);
        }
示例#28
0
        /// <summary>
        /// Sets authorization header.
        /// </summary>
        /// <returns>Authorization header</returns>
        private async Task <string> AuthorizationHeader()
        {
            if (!string.IsNullOrEmpty(_authorizationHeader) &&
                (DateTime.UtcNow.AddSeconds(60) < AuthenticationResult.ExpiresOn))
            {
                return(_authorizationHeader);
            }

            var uri = new UriBuilder(_settings.AzureAuthEndpoint)
            {
                Path = _settings.AadTenant
            };

            var aosUriAuthUri             = new Uri(_settings.AosUri);
                        string aosUriAuth = aosUriAuthUri.GetLeftPart(UriPartial.Authority);

            var authenticationContext = new AuthenticationContext(uri.ToString(), validateAuthority: false);

            if (_settings.UseServiceAuthentication)
            {
                var credentials = new ClientCredential(_settings.AadClientId.ToString(), _settings.AadClientSecret);

                AuthenticationResult = await _retryPolicy.ExecuteAsync(() => authenticationContext.AcquireTokenAsync(aosUriAuth, credentials));
            }
            else
            {
                var credentials = new UserPasswordCredential(_settings.UserName, _settings.UserPassword);

                AuthenticationResult = await _retryPolicy.ExecuteAsync(() => authenticationContext.AcquireTokenAsync(aosUriAuth, _settings.AadClientId.ToString(), credentials));
            }

            return(_authorizationHeader = AuthenticationResult.CreateAuthorizationHeader());
        }
示例#29
0
        /// <summary>
        /// Gets the <see cref="SubscriptionCloudCredentials"/> instance as Azure subscription credentials.
        /// </summary>
        /// <returns>Returns the <see cref="SubscriptionCloudCredentials"/> instance as Azure subscription credentials.</returns>
        public async Task <SubscriptionCloudCredentials> GetCredentialsAsync()
        {
#if !TEST
            Console.WriteLine("Acquiring credentials ...");
#endif

            IAuthenticationResultWrapper result;
            if (this._auth.UseServicePrinciple)
            {
                var cc = new ClientCredential(this._auth.ClientId, this._auth.ClientSecret);
                result = await this._authenticationContext.AcquireTokenAsync($"{this._auth.ManagementInstanceUrl.TrimEnd('/')}/", cc).ConfigureAwait(false);

#if !TEST
                Console.WriteLine("Credentials acquired");
#endif
                return(new TokenCloudCredentials(this._appInsights.SubscriptionId, result.AccessToken));
            }

            var uc = new UserPasswordCredential(this._auth.Username, this._auth.Password);
            result = await this._authenticationContext.AcquireTokenAsync($"{this._auth.ManagementInstanceUrl.TrimEnd('/')}/", this._auth.ClientId, uc).ConfigureAwait(false);

#if !TEST
            Console.WriteLine("Credentials acquired");
#endif
            return(new TokenCloudCredentials(this._appInsights.SubscriptionId, result.AccessToken));
        }
        /// <summary>
        /// Retrieves an authentication header from the service.
        /// </summary>
        /// <returns>The authentication header for the Web API call.</returns>
        public static string GetAuthenticationHeader(bool useWebAppAuthentication = false)
        {
            string aadTenant      = ClientConfiguration.Default.ActiveDirectoryTenant;
            string aadClientAppId = ClientConfiguration.Default.ActiveDirectoryClientAppId;
            string aadResource    = ClientConfiguration.Default.ActiveDirectoryResource;

            AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
            AuthenticationResult  authenticationResult;

            if (useWebAppAuthentication)
            {
                string aadClientAppSecret = ClientConfiguration.Default.ActiveDirectoryClientAppSecret;
                var    creadential        = new ClientCredential(aadClientAppId, aadClientAppSecret);
                authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
            }
            else
            {
                // OAuth through username and password.
                string username = ClientConfiguration.Default.UserName;
                string password = ClientConfiguration.Default.Password;

                // Get token object
                var userCredential = new UserPasswordCredential(username, password);
                authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, aadClientAppId, userCredential).Result;
            }

            // Create and get JWT token
            return(authenticationResult.CreateAuthorizationHeader());
        }
 private AuthenticationResult GetToken()
 {
     string upn = string.Format("{0}@{1}", ConfigurationManager.AppSettings["MediaServiceAccountName"], ConfigurationManager.AppSettings["AadTenant"]);
     var credentials = new UserPasswordCredential(upn, ConfigurationManager.AppSettings["MediaServiceAccountKey"]);
     //TODO: May be use the graph API to find the SDK App from the tenant by name or by URI.
     var clientId = ConfigurationManager.AppSettings["AadClientId"];
     var result = _context.AcquireTokenAsync(
         ConfigurationManager.AppSettings["MediaServicesUri"],
         clientId,
         credentials).Result;
     return result;
 }