Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Several question related to this page #22657

Closed
hanslai opened this issue Jul 5, 2021 · 2 comments
Closed

Several question related to this page #22657

hanslai opened this issue Jul 5, 2021 · 2 comments
Assignees
Labels
Blazor Source - Docs.ms Docs Customer feedback via GitHub Issue support-request

Comments

@hanslai
Copy link

hanslai commented Jul 5, 2021

  1. GraphClientExtensions this class's default request url is https://graph.microsoft.com/v1.0/me, which does not work for Azure China, and there is no doc on how to change the base URI.

Updated the code as below in GraphExample.razor for Azure China

<h3>Graph Client Example</h3>

@if (user == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <p>Mobile Phone: @user.MobilePhone</p>
}

@code {
    private User user;

    protected async override Task OnInitializedAsync()
    {
        GraphClient.BaseUrl = "https://microsoftgraph.chinacloudapi.cn/v1.0/";
        var request = GraphClient.Me.Request();
        var user = await request.GetAsync();
    }
}

Where is the best place to change the base url?

  1. Confused about the where to add the scope placeholders
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            var result = await TokenProvider.RequestAccessToken(
                new AccessTokenRequestOptions()
                {
                    Scopes = new[] { "{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}" }
                });

            if (result.TryGetToken(out var token))
            {
                request.Headers.Authorization ??= new AuthenticationHeaderValue(
                    "Bearer", token.Value);
            }
        }

and
builder.Services.AddGraphClient("{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}");

Do I need to put the scopes in both places or one of the two places is good enough?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

@dotnet-bot dotnet-bot added Blazor Source - Docs.ms Docs Customer feedback via GitHub Issue labels Jul 5, 2021
@guardrex guardrex self-assigned this Jul 5, 2021
@guardrex
Copy link
Collaborator

guardrex commented Jul 5, 2021

Hello @hanslai ...

On 1 ... The code shown here is a general guideline for the developer to further modify for their specific use cases.

One approach might be to set the base URL where the GraphServiceClient is returned in GraphClientExtensions.AddGraphClient. Instead of what the topic shows for .....

services.AddScoped(sp =>
{
    return new GraphServiceClient(
        sp.GetRequiredService<IAuthenticationProvider>(),
        sp.GetRequiredService<IHttpProvider>());
});

... you might try something like ...

services.AddScoped(sp =>
{
    var client = new GraphServiceClient(
        sp.GetRequiredService<IAuthenticationProvider>(),
        sp.GetRequiredService<IHttpProvider>());

    client.BaseUrl = "https://microsoftgraph.chinacloudapi.cn/v1.0/";

    return client;
});

... and even that URL might be something that you load from app settings and not hardcode into the service registration.

I've added your issue to my UE ("user experience" ... i.e., total overhaul) tracking issue so that I can take a closer look at this when I reach this topic for updates. What I might do is make the approach of setting the base URL either a new section or refactor the code so that one explicitly sets it via app settings. I'm going to close this issue, but I will review this issue when I reach the topic for work later.

On 2 ... BOTH (as the topic states and shows in the first section) ...

Here .......

Scopes = new[] { "{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}" }

... and here ...

builder.Services.AddGraphClient("{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}");

@guardrex
Copy link
Collaborator

guardrex commented Dec 9, 2022

FYI @hanslai ... I've finally reached this topic for work 😅. This was the soonest that I could reach the topic. We've been VERY busy around here for a long time. I'm actually working over and enhancing all of the Blazor security guidance right now EOY, perhaps even into early January.

I had marked your issue on my tracking issue to make sure that I would address your concerns. I just found out something that will become part of the updates, and I'm going to leave it here, too, in case anyone searches and finds this issue.

You were asking about setting the base URL in the Graph SDK scenario. Consider this approach ...

appsettings.json:

"MicrosoftGraph": {
  "BaseUrl": "https://graph.microsoft.com",
  "Version: "v1.0",
  "Scopes": [
    "user.read"
  ]
}

For the GraphServiceClient, pass in a baseUrl (along with the scopes, which I'm also going to take from configuration for the upcoming updates to the topic) ...

public static IServiceCollection AddGraphClient(
    this IServiceCollection services, string? baseUrl, List<string>? scopes)
{
    services.Configure<RemoteAuthenticationOptions<MsalProviderOptions>>(
        options =>
        {
            scopes?.ForEach((scope) =>
            {
                options.ProviderOptions.AdditionalScopesToConsent.Add(scope);
            });
        });

    services.AddScoped<IAuthenticationProvider, GraphAuthenticationProvider>();

    services.AddScoped<IHttpProvider, HttpClientHttpProvider>(sp =>
        new HttpClientHttpProvider(new HttpClient()));

    services.AddScoped(sp =>
    {
        return new GraphServiceClient(
            baseUrl,
            sp.GetRequiredService<IAuthenticationProvider>(),
            sp.GetRequiredService<IHttpProvider>());
    });

    return services;
}

... and then in Program.cs, the baseUrl holds the concatenated BaseUrl and the Version from the configuration. I also take the scopes from config. These are passed to AddGraphClient.

var baseUrl = string.Join("/", 
    builder.Configuration.GetSection("MicrosoftGraph")["BaseUrl"], 
    builder.Configuration.GetSection("MicrosoftGraph")["Version"]);
var scopes = builder.Configuration.GetSection("MicrosoftGraph:Scopes")
    .Get<List<string>>();

builder.Services.AddGraphClient(baseUrl, scopes);

You can see there how the baseUrl is going right into one of the overloads of GraphServiceClient at ....

return new GraphServiceClient(
    baseUrl,
    sp.GetRequiredService<IAuthenticationProvider>(),
    sp.GetRequiredService<IHttpProvider>());

That seems to be the cleanest way (with config) to get a base Url into this Graph SDK approach.

I'll ping you on the PR later so that you can see all of the updates that I'm working on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Blazor Source - Docs.ms Docs Customer feedback via GitHub Issue support-request
Projects
Archived in project
Development

No branches or pull requests

3 participants