public async Task <ActionResult> LandingExternal(MsalOauthResponse response) { if (string.IsNullOrWhiteSpace(response.Code)) { return(Json(response, "application/json", JsonRequestBehavior.AllowGet)); } var state = OAuth2Helper.ParseState(response.State); if (state.ClientId == null) { return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, "Invalid session data returned after login from M365")); } var tenant = await _mediator.Send(new QueryTenantByClientId(state.ClientId)); if (tenant.TenantId != state.Tenant) { return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, "Invalid tenant returned after login from M365")); } var tokenResponse = await OAuth2Helper.AcquireTokenAsync(new AcquireTokenRequest { Tenant = tenant.TenantId, ClientId = tenant.ClientId, Secret = tenant.Secret, ResponseCode = response.Code, CodeVerifier = state.CodeVerifier, RedirectUri = $"{Request.GetBaseUrl()}{Url.Action("LandingExternal")}" }); await _mediator.Send(new SaveEmailAccountTokenCommand { Email = state.Email, AccessToken = tokenResponse.AccessToken, RefreshToken = tokenResponse.RefreshToken }); return(View(tokenResponse)); }