Created
September 12, 2021 07:51
-
-
Save justinyoo/38ae8fdd9ac6161551a9aee0d15b76e7 to your computer and use it in GitHub Desktop.
Accessing MSGraph from Blazor WASM Running on ASWA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| https://<azure_static_webapp>.azurestaticapps.net/.auth/login/aad |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "clientPrincipal": { | |
| "identityProvider":"aad", | |
| "userId":"<guid>", | |
| "userDetails":"<logged_in_email>", | |
| "userRoles":[ | |
| "anonymous", | |
| "authenticated" | |
| ] | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ewogICJpZGVudGl0eVByb3ZpZGVyIjoiYWFkIiwKICAidXNlcklkIjoiPGd1aWQ+IiwKICAidXNlckRldGFpbHMiOiI8bG9nZ2VkX2luX2VtYWlsPiIsCiAgInVzZXJSb2xlcyI6WwogICAgImFub255bW91cyIsCiAgICAiYXV0aGVudGljYXRlZCIKICBdCn0= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "Values": { | |
| "LoginUri": "https://login.microsoftonline.com/", | |
| "TenantId": "<tenant_id>", | |
| "ClientId": "<client_id>", | |
| "ClientSecret": "<client_secret>", | |
| "ApiHost": "https://graph.microsoft.com/", | |
| "BaseUrl": "v1.0/" | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "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", | |
| ... | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var loggedInUser = new LoggedInUser(user); | |
| return new OkObjectResult(loggedInUser); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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