Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Accessing MSGraph from Blazor WASM Running on ASWA
https://<azure_static_webapp>.azurestaticapps.net/.auth/login/aad
var baseUri = "https://<azure_static_webapp>.azurestaticapps.net";
var http = new HttpClient() { BaseAddress = new Uri(baseUri) };
var response = await http.GetStringAsync("/.auth/me").ConfigureAwait(false);
{
"clientPrincipal": {
"identityProvider":"aad",
"userId":"<guid>",
"userDetails":"<logged_in_email>",
"userRoles":[
"anonymous",
"authenticated"
]
}
}
ewogICJpZGVudGl0eVByb3ZpZGVyIjoiYWFkIiwKICAidXNlcklkIjoiPGd1aWQ+IiwKICAidXNlckRldGFpbHMiOiI8bG9nZ2VkX2luX2VtYWlsPiIsCiAgInVzZXJSb2xlcyI6WwogICAgImFub255bW91cyIsCiAgICAiYXV0aGVudGljYXRlZCIKICBdCn0=
public class ClientPrincipal
{
[JsonProperty("identityProvider")]
public string IdentityProvider { get; set; }
[JsonProperty("userId")]
public string UserId { get; set; }
[JsonProperty("userDetails")]
public string UserDetails { get; set; }
[JsonProperty("userRoles")]
public IEnumerable<string> UserRoles { get; set; }
}
var bytes = Convert.FromBase64String((string)req.Headers["x-ms-client-principal"]);
var json = Encoding.UTF8.GetString(bytes);
var principal = JsonConvert.DeserializeObject<ClientPrincipal>(json);
var userEmail = principal.UserDetails;
{
"Values": {
"LoginUri": "https://login.microsoftonline.com/",
"TenantId": "<tenant_id>",
"ClientId": "<client_id>",
"ClientSecret": "<client_secret>",
"ApiHost": "https://graph.microsoft.com/",
"BaseUrl": "v1.0/"
}
}
private async Task<string> GetAccessTokenAsync()
{
var apiHost = Environment.GetEnvironmentVariable("ApiHost");
var scopes = new [] { $"{apiHost.TrimEnd('/')}/.default" };
var options = new ConfidentialClientApplicationOptions()
{
Instance = Environment.GetEnvironmentVariable("LoginUri"),
TenantId = Environment.GetEnvironmentVariable("TenantId"),
ClientId = Environment.GetEnvironmentVariable("ClientId"),
ClientSecret = Environment.GetEnvironmentVariable("ClientSecret"),
};
var authority = $"{options.Instance.TrimEnd('/')}/{options.TenantId}";
var app = ConfidentialClientApplicationBuilder
.Create(options.ClientId)
.WithClientSecret(options.ClientSecret)
.WithAuthority(authority)
.Build();
var result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync()
.ConfigureAwait(false);
var accessToken = result.AccessToken;
return accessToken;
}
private async Task<GraphServiceClient> GetGraphClientAsync()
{
var baseUri = $"{Environment.GetEnvironmentVariable("ApiHost").TrimEnd('/')}/{Environment.GetEnvironmentVariable("BaseUrl")}";
var provider = new DelegateAuthenticationProvider(async p =>
{
var accessToken = await this.GetAccessTokenAsync().ConfigureAwait(false);
p.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
});
var client = new GraphServiceClient(baseUri, provider);
return await Task.FromResult(client).ConfigureAwait(false);
}
var client = await this.GetGraphClientAsync().ConfigureAwait(false);
var users = await client.Users.Request().GetAsync().ConfigureAwait(false);
var user = users.SingleOrDefault(p => p.Mail == userEmail);
if (user == null)
{
return new NotFoundResult();
}
{
"accountEnabled": null,
"ageGroup": null,
"assignedLicenses": null,
...
"displayName": "Justin Yoo",
...
"givenName": "Justin",
...
"mail": "justin.yoo@<external_tenant_name>.onmicrosoft.com",
...
"surname": "Yoo",
"usageLocation": null,
"userPrincipalName": "justin.yoo_<external_tenant_name>.onmicrosoft.com#EXT#@<tenant_name>.onmicrosoft.com",
...
}
public class LoggedInUser
{
public LoggedInUser(User user)
{
this.Upn = user?.UserPrincipalName;
this.DisplayName = user?.DisplayName;
this.Email = user?.Mail;
}
[JsonProperty("upn")]
public virtual string Upn { get; set; }
[JsonProperty("displayName")]
public virtual string DisplayName { get; set; }
[JsonProperty("email")]
public virtual string Email { get; set; }
}
var loggedInUser = new LoggedInUser(user);
return new OkObjectResult(loggedInUser);
protected async Task<LoggedInUserDetails> GetLoggedInUserDetailsAsync()
{
var details = default(LoggedInUserDetails);
try
{
using (var response = await this._http.GetAsync("/api/users/get").ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
details = JsonSerializer.Deserialize<LoggedInUserDetails>(json);
}
}
catch
{
}
return details;
}
<div class="page">
...
<div class="main">
...
<div class="top-row px-4 text-end">
<span class="px-4">@DisplayName</span> | <a href="/logout">Logout</a>
</div>
...
</div>
</div>
@code {
protected string DisplayName;
protected override async Task OnInitializedAsync()
{
var loggedInUser = await GetLoggedInUserDetailsAsync().ConfigureAwait(false);
DisplayName = loggedInUser?.DisplayName ?? "Not a registered user";
}
}
<div class="page">
...
<div class="main">
...
<div class="top-row px-4 text-end">
<span class="px-4">@DisplayName</span> | <a href="/logout">로그아웃</a>
</div>
...
</div>
</div>
@code {
protected string DisplayName;
protected override async Task OnInitializedAsync()
{
var loggedInUser = await GetLoggedInUserDetailsAsync().ConfigureAwait(false);
DisplayName = loggedInUser?.DisplayName ?? "등록된 사용자 아님";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment