Esempio n. 1
0
 private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes, string tenantId)
 {
     return(GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
     {
         string result = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);
         return result;
     }, _webOptions.GraphApiUrl));
 }
        public async Task <IActionResult> Profile()
        {
            var accessToken =
                await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead });

            var me = await graphApiOperations.GetUserInformation(accessToken);

            var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken);

            ViewData["Me"]    = me;
            ViewData["Photo"] = photo;

            return(View());
        }
        public async Task <IActionResult> Index()
        {
            // Using group ids/names in the IsInRole method
            // var isinrole = User.IsInRole("8873daa2-17af-4e72-973e-930c94ef7549");

            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

            User me = await graphService.GetMeAsync(accessToken);

            ViewData["Me"] = me;

            try
            {
                var photo = await graphService.GetMyPhotoAsync(accessToken);

                ViewData["Photo"] = photo;
            }
            catch
            {
                //swallow
            }

            IList <Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

            ViewData["Groups"] = groups;

            return(View());
        }
Esempio n. 4
0
        /// <summary>
        /// Adds claims for the currently authenticated user and returns a value indicating whether
        /// the pipeline should continue processing or not.
        /// </summary>
        /// <param name="httpContext">The <see cref="HttpContext"/> for the current request.</param>
        /// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
        /// <returns>
        /// <c>true</c> if the next middleware should run; otherwise, <c>false</c>.
        /// </returns>
        public async Task <bool> AddClaimsAsync(HttpContext httpContext, CancellationToken cancellationToken)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            try
            {
                var claimsPrincipal = httpContext.User as ClaimsPrincipal;
                if (claimsPrincipal?.Identity?.IsAuthenticated != true)
                {
                    return(true);
                }

                var accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(Options.RequestedScopes).ConfigureAwait(false);
                await AddGroupsClaimsAsync(claimsPrincipal, accessToken, cancellationToken).ConfigureAwait(false);

                return(true);
            }
            catch (MsalUiRequiredException ex)
            {
                _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader(Options.RequestedScopes, ex);
                return(false);
            }
        }
        public async Task <IActionResult> Index()
        {
            // Using group ids/names in the IsInRole method
            // var isinrole = User.IsInRole("a9cccbf0-6fb5-41ec-a45b-e76e57fd241a");

            ViewData["User"] = HttpContext.User;

            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

            User me = await graphService.GetMeAsync(accessToken);

            ViewData["Me"] = me;

            try
            {
                var photo = await graphService.GetMyPhotoAsync(accessToken);

                ViewData["Photo"] = photo;
            }
            catch
            {
                //swallow
            }

            IList <Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

            ViewData["Groups"] = groups;

            return(View());
        }
Esempio n. 6
0
 private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes)
 {
     return(GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
     {
         string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);
         return result;
     }, "https://graph.microsoft.com/beta"));
 }
Esempio n. 7
0
 private GraphServiceClient GetGraphServiceClient()
 {
     return(GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
     {
         string result = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(_azureAdOptions.GraphScopes.Split(' '));
         return result;
     }, _azureAdOptions.GraphApiUrl));
 }
Esempio n. 8
0
        public async Task OnGet()
        {
            //var accessToken = HttpContext.GetTokenAsync(AzureADDefaults.AuthenticationScheme, "access_token").Result;
            //var idToken = HttpContext.GetTokenAsync(AzureADDefaults.AuthenticationScheme, "id_token").Result;
            //var claimsToken = User.Claims.FirstOrDefault(c => c.Type == "token")?.Value;
            //Redirect($"https://localhost:/#id_token={claimsToken}");

            AccessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { "api://a1378021-3598-476b-bfc6-80fdd56275c9/Weather.Read" });
        }
        public async Task <Subscription> GetSubscriptionAsync(Guid tenantId)
        {
            var token = _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(_configuration["SaaSWebApi:Scopes"].Split(' '));

            using var requestMessage = new HttpRequestMessage(HttpMethod.Get,
                                                              $"{_configuration["SaaSWebApi:BaseAddress"]}/api/Subscriptions");

            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await token);

            var httpClient = _httpClientFactory.CreateClient();
            var response   = await httpClient.SendAsync(requestMessage);

            var json = await response.Content.ReadAsStringAsync();

            var subscription = JsonConvert.DeserializeObject <List <Subscription> >(json)
                               .Where(subscription => subscription.TenantId == tenantId).FirstOrDefault();

            return(subscription);
        }
Esempio n. 10
0
        public async Task <List <Deals> > GetDealsOnBehalfOfUser()
        {
            string[] scopes = { ".default" };

            // we use MSAL.NET to get a token to call the API On Behalf Of the current user
            try
            {
                string accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);

                dynamic me = await GetDealsOnBehalfOfUser(accessToken);

                return(me);
            }
            catch (MsalUiRequiredException ex)
            {
                _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader(scopes, ex);
                return(null);
            }
        }
Esempio n. 11
0
        public async Task <IActionResult> Groups()
        {
            string[] scopes = new[] { GraphScopes.DirectoryReadAll };

            GraphServiceClient graphServiceClient = GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
            {
                string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);
                return(result);
            }, webOptions.GraphApiUrl);

            var groups = await graphServiceClient.Me.MemberOf.Request().GetAsync();

            ViewData["Groups"] = groups.CurrentPage;

            return(View());
        }
Esempio n. 12
0
        public async Task <IActionResult> Index()
        {
            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

            User me = await graphService.GetMeAsync(accessToken);

            var photo = await graphService.GetMyPhotoAsync(accessToken);

            IList <Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

            ViewData["Me"]     = me;
            ViewData["Photo"]  = photo;
            ViewData["Groups"] = groups;

            return(View());
        }
        public async Task <string> CallGraphApiOnBehalfOfUser()
        {
            string[] scopes = { "user.read" };

            // we use MSAL.NET to get a token to call the API On Behalf Of the current user
            try
            {
                string accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);

                dynamic me = await CallGraphApiOnBehalfOfUser(accessToken);

                return(me.userPrincipalName);
            }
            catch (MsalUiRequiredException ex)
            {
                _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader(scopes, ex);
                return(string.Empty);
            }
        }
Esempio n. 14
0
        public async Task <List <IEFObject> > SetupAsync(string domainId, bool readOnly)
        {
            using (_logger.BeginScope("SetupAsync: {0} - Read only: {1}", domainId, readOnly))
            {
                _readOnly = readOnly;
                try
                {
                    var token = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(
                        readOnly?Constants.ReadOnlyScopes : Constants.ReadWriteScopes,
                        domainId);

                    _http = new HttpClient();
                    _http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

                    _actions = new List <IEFObject>();
                    await SetupIEFAppsAsync(domainId);
                    await SetupKeysAsync();

                    var extAppId = await GetAppIdAsync("b2c-extensions-app");

                    _actions.Add(new IEFObject()
                    {
                        Name   = "Extensions app: appId",
                        Id     = extAppId,
                        Status = String.IsNullOrEmpty(extAppId) ? IEFObject.S.NotFound : IEFObject.S.Existing
                    });
                    extAppId = await GetAppIdAsync("b2c-extensions-app", true);

                    _actions.Add(new IEFObject()
                    {
                        Name   = "Extensions app: objectId",
                        Id     = extAppId,
                        Status = String.IsNullOrEmpty(extAppId) ? IEFObject.S.NotFound : IEFObject.S.Existing
                    });
                } catch (Exception ex)
                {
                    _logger.LogError(ex, "SetupAsync failed");
                }
            }
            return(_actions);
        }
        public async Task <IActionResult> Edit(int id)
        {
            TodoItem todoItem = await _todoItemService.Get(id, User);

            if (todoItem == null)
            {
                TempData["ErrorMessage"] = "Item not found";
                return(RedirectToAction("Error", "Home"));
            }

            var userTenant = User.GetTenantId();

            // Acquiring token for graph in the signed-in users tenant, so it can be used to retrieve all the users from their tenant
            var graphAccessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new string[] { GraphScope.UserReadAll }, userTenant);

            TempData["UsersDropDown"] = (await _msGraphService.GetUsersAsync(graphAccessToken))
                                        .Select(u => new SelectListItem
            {
                Text  = u.UserPrincipalName,
                Value = u.Id
            }).ToList();

            return(View(todoItem));
        }
Esempio n. 16
0
        public async Task <IActionResult> OnGet()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            foreach (Claim claim in User.Claims)
            {
                if (claim.Type.Contains("objectidentifier") || claim.Type.Contains("oid"))
                {
                    oid = claim.Value;
                }
                if (claim.Type.Contains("tenant") || claim.Type.Contains("tid"))
                {
                    tenantId = claim.Value;
                }
                if (claim.Type == "name")
                {
                    name = claim.Value;
                }
                if (claim.Type == "preferred_username")
                {
                    preferredUsername = claim.Value;
                }
                //Console.WriteLine("### Claim: " + claim.Type + " == " + claim.Value);
            }

            username = User.Identity.Name;

            // Graph stuff
            // Acquire the access token
            try {
                string[] scopes      = new string[] { "user.read" };
                string   accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);

                // Create a client
                var graphClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(
                        (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                    return(Task.FromResult(0));
                }));

                // Fetch user details
                var user = await graphClient.Me
                           .Request()
                           .GetAsync();

                graphData.Add("UPN", user.UserPrincipalName);
                graphData.Add("Given Name", user.GivenName);
                graphData.Add("Display Name", user.DisplayName);
                graphData.Add("Office", user.OfficeLocation);
                graphData.Add("Mobile", user.MobilePhone);
                graphData.Add("Other Phone", user.BusinessPhones.Count() > 0 ? user.BusinessPhones.First() : "");
                graphData.Add("Job Title", user.JobTitle);

                // Fetch user photo
                try {
                    Stream pictureStream = await graphClient
                                           .Me
                                           .Photos["432x432"]
                                           .Content
                                           .Request()
                                           .GetAsync();

                    // Convert to bytes
                    graphPhoto = ToByteArray(pictureStream);
                } catch (Exception e) {
                    _logger.LogWarning(e.ToString());
                }
            } catch (Exception) {
                return(Redirect("/"));
            }
            return(Page());
        }
Esempio n. 17
0
 /// <summary>
 /// Gets a new access token on behalf of the user
 /// </summary>
 /// <returns>JWT in string format</returns>
 public async Task <string> GetAccessToken()
 {
     return(await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { this.backendScope }));
 }
Esempio n. 18
0
        public async Task <List <IEFObject> > SetupAsync(string domainId, bool removeFb, string dirDomainName, bool initialisePhoneSignInJourneys, string PolicySample)
        {
            using (_logger.BeginScope("SetupAsync: {0} - Read only: {1}", domainId, removeFb))
            {
                _actions = new List <IEFObject>();
                if (PolicySample != "null")
                {
                    var token = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(
                        Constants.ReadWriteScopes,
                        domainId);

                    _http = new HttpClient();
                    _http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

                    HttpClient _httpToRepoAPI    = new HttpClient();
                    string     urlToFetchPolices = "https://-/api/FetchRepo?policyname=" + PolicySample;
                    var        json = await _httpToRepoAPI.GetStringAsync(urlToFetchPolices);

                    var value = JArray.Parse(json);

                    var rawPolicyFileNames = new List <string>();
                    foreach (string url in value)
                    {
                        rawPolicyFileNames.Add(url);
                    }
                    //if we found ext file, move to top
                    var regexExtensions = @"\w*Extensions\w*";
                    var indexExtensions = -1;
                    indexExtensions = rawPolicyFileNames.FindIndex(d => regexExtensions.Any(s => Regex.IsMatch(d.ToString(), regexExtensions)));
                    if (indexExtensions > -1)
                    {
                        rawPolicyFileNames.Insert(0, rawPolicyFileNames[indexExtensions]);
                        rawPolicyFileNames.RemoveAt(indexExtensions + 1);
                    }
                    //if we found base file, move to top
                    var regexBase = @"\w*Base\w*";
                    var indexBase = -1;
                    indexBase = rawPolicyFileNames.FindIndex(d => regexBase.Any(s => Regex.IsMatch(d.ToString(), regexBase)));
                    if (indexBase > -1)
                    {
                        rawPolicyFileNames.Insert(0, rawPolicyFileNames[indexBase]);
                        rawPolicyFileNames.RemoveAt(indexBase + 1);
                    }
                    var policyFileList = new List <string>();

                    foreach (string url in rawPolicyFileNames)
                    {
                        policyFileList.Add(new WebClient().DownloadString(url));
                    }

                    for (int i = 0; i < policyFileList.Count; i++)
                    {
                        policyFileList[i] = policyFileList[i].Replace("yourtenant.onmicrosoft.com", dirDomainName + ".onmicrosoft.com");
                    }


                    //build k-v pair list of policyId:policyFilen
                    var policyList = buildPolicyListByPolicyId(policyFileList);
                    await UploadPolicyFiles(policyList);

                    return(_actions);
                }


                if (PolicySample == "null")
                {
                    _removeFb = removeFb;
                    try
                    {
                        var token = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(
                            Constants.ReadWriteScopes,
                            domainId);

                        _http = new HttpClient();
                        _http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);


                        await SetupIEFAppsAsync(domainId);
                        await SetupKeysAsync();

                        var extAppId = await GetAppIdAsync("b2c-extensions-app");

                        _actions.Add(new IEFObject()
                        {
                            Name   = "Extensions app: appId",
                            Id     = extAppId,
                            Status = String.IsNullOrEmpty(extAppId) ? IEFObject.S.NotFound : IEFObject.S.Exists
                        });
                        extAppId = await GetAppIdAsync("b2c-extensions-app", true);

                        _actions.Add(new IEFObject()
                        {
                            Name   = "Extensions app: objectId",
                            Id     = extAppId,
                            Status = String.IsNullOrEmpty(extAppId) ? IEFObject.S.NotFound : IEFObject.S.Exists
                        });
                    } catch (Exception ex)
                    {
                        _logger.LogError(ex, "SetupAsync failed");
                    }


                    //actions structure
                    //ief app 0
                    //proxyief app 1
                    //extension appid 4
                    //extension objectId 5


                    //download localAndSocialStarterPack
                    // returns list policyId: policyXML
                    var policyList = GetPolicyFiles(removeFb, dirDomainName, initialisePhoneSignInJourneys);

                    // Strip UJs from SocialLocalMFA base file
                    // Take UJs from Local base file and put it in Extensions file

                    if (removeFb)
                    {
                        // Remove default social and local and mfa user journeys
                        XmlDocument socialAndLocalBase = new XmlDocument();
                        socialAndLocalBase.LoadXml(policyList.First(kvp => kvp.Key == "B2C_1A_TrustFrameworkBase").Value);
                        var nsmgr = new XmlNamespaceManager(socialAndLocalBase.NameTable);
                        nsmgr.AddNamespace("xsl", "http://schemas.microsoft.com/online/cpim/schemas/2013/06");

                        XmlNode socialAndMFAJourneys = socialAndLocalBase.SelectSingleNode("/xsl:TrustFrameworkPolicy/xsl:UserJourneys", nsmgr);
                        socialAndMFAJourneys.RemoveAll();
                        XmlNode parentSocialAndMFAJourneys = socialAndMFAJourneys.ParentNode;
                        parentSocialAndMFAJourneys.RemoveChild(socialAndMFAJourneys);

                        XmlNode facebookTP = socialAndLocalBase.SelectSingleNode("/xsl:TrustFrameworkPolicy/xsl:ClaimsProviders/xsl:ClaimsProvider[1]", nsmgr);
                        facebookTP.RemoveAll();
                        XmlNode parentfacebookTP = facebookTP.ParentNode;
                        parentfacebookTP.RemoveChild(facebookTP);

                        //policyList.RemoveAll(kvp => kvp.Key == "B2C_1A_TrustFrameworkBase");
                        policyList["B2C_1A_TrustFrameworkBase"] = socialAndLocalBase.OuterXml;
                        //policyList.Add(new KeyValuePair<string, string>("B2C_1A_TrustFrameworkBase", socialAndLocalBase.OuterXml));

                        // Insert user journeys from LocalAccounts base file into Ext file.
                        XmlDocument localBase     = new XmlDocument();
                        string      baseFileLocal = new WebClient().DownloadString("https://raw.githubusercontent.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/master/LocalAccounts/TrustFrameworkBase.xml");
                        localBase.LoadXml(baseFileLocal);
                        XmlNode localBaseJourneys = localBase.SelectSingleNode("/xsl:TrustFrameworkPolicy/xsl:UserJourneys", nsmgr);

                        string localJourneysString = localBaseJourneys.OuterXml;
                        localJourneysString.Replace("<UserJourneys xmlns=\"http://schemas.microsoft.com/online/cpim/schemas/2013/06\">", "<UserJourneys>");
                        string extFile = policyList.First(kvp => kvp.Key == "B2C_1A_TrustFrameworkExtensions").Value;
                        extFile = extFile.Replace("</TrustFrameworkPolicy>", localJourneysString + "</TrustFrameworkPolicy>");
                        extFile.Replace("yourtenant.onmicrosoft.com", dirDomainName + ".onmicrosoft.com");

                        //policyList.RemoveAll(kvp => kvp.Key == "B2C_1A_TrustFrameworkExtensions");
                        //policyList.Add(new KeyValuePair<string, string>("B2C_1A_TrustFrameworkExtensions", extFile));

                        policyList["B2C_1A_TrustFrameworkExtensions"] = extFile;
                    }

                    // setup login-noninteractive and ext attribute support
                    policyList = SetupAADCommon(policyList, initialisePhoneSignInJourneys);

                    if (!removeFb)
                    {
                        await SetupDummyFacebookSecret(removeFb);
                    }
                    else
                    {
                        _actions.Add(new IEFObject()
                        {
                            Name   = "Facebook secret",
                            Id     = "B2C_FacebookSecret",
                            Status = IEFObject.S.Skipped
                        });
                    }

                    await UploadPolicyFiles(policyList);
                    await CreateJwtMsTestApp();
                }
            }
            return(_actions);
        }
Esempio n. 19
0
        public async Task <IActionResult> Get()
        {
            var accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { "api://a1378021-3598-476b-bfc6-80fdd56275c9/Weather.Read" });

            return(Ok(new { token = accessToken }));
        }
Esempio n. 20
0
 public async Task <IActionResult> GetSaaSWebApiAccessToken()
 {
     return(Ok(await _tokenAcquisition
               .GetAccessTokenOnBehalfOfUserAsync(_saaSWebApiOptions.Scopes.Split(' '))));
 }