public async Task <IActionResult> AADCallback(string code, string state, string error, string error_description) { if (!string.IsNullOrEmpty(error) && !string.IsNullOrEmpty(error_description)) { throw new Exception($"AADLogin Error: {error} => {error_description.Split('\r').FirstOrDefault()}"); } AccessTokenModel accessToken = await GetAADAccessToken(code); if (string.IsNullOrEmpty(accessToken.Error)) { throw new Exception($"{accessToken.Error} => {accessToken.ErrorDescription}"); } MeModel me = await GetAADMe(accessToken.AccessToken); if (me.Error != null) { throw new Exception($"{me.Error.Code} => {me.Error.Message}"); } var user = authManager.SignInAAD(me.UserPrincipalName); if (user == null) { throw new Exception("User not found!"); } await CreateAuthCookie(user, true); return(RedirectToAction("Index", "Home")); }
private async Task <MeModel> GetAADMe(string accessToken) { MeModel me = null; using (var client = new HttpClient()) { var meURL = $"https://graph.microsoft.com/v1.0/me"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var meResponse = await client.GetAsync(meURL); me = JsonConvert.DeserializeObject <MeModel>(await meResponse.Content.ReadAsStringAsync()); } return(me); }