protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (Request.IsAuthenticated) { // Get the user's token cache var tokenStore = new SessionTokenStore(null, System.Web.HttpContext.Current, ClaimsPrincipal.Current); if (tokenStore.HasData()) { // Add the user to the view bag ViewBag.User = tokenStore.GetUserDetails(); ViewBag.Sid = tokenStore.GetSid(); } else { // The session has lost data. This happens often // when debugging. Log out so the user can log back in Request.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); filterContext.Result = RedirectToAction("Index", "Home"); } } base.OnActionExecuting(filterContext); }
public static GraphServiceClient GetAuthenticatedClient() { return(new GraphServiceClient( new DelegateAuthenticationProvider( async(requestMessage) => { var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, ClaimsPrincipal.Current); var accounts = await idClient.GetAccountsAsync(); // By calling this here, the token can be refreshed // if it's expired right before the Graph call is made var scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); }))); }
private static GraphServiceClient GetAuthenticatedClient() { return(new GraphServiceClient( new DelegateAuthenticationProvider( async(requestMessage) => { // Get the signed in user's id and create a token cache string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId, new HttpContextWrapper(HttpContext.Current)); var idClient = new ConfidentialClientApplication( appId, redirectUri, new ClientCredential(appSecret), tokenStore.GetMsalCacheInstance(), null); var accounts = await idClient.GetAccountsAsync(); // By calling this here, the token can be refreshed // if it's expired right before the Graph call is made var result = await idClient.AcquireTokenSilentAsync( graphScopes.Split(' '), accounts.FirstOrDefault()); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); }))); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (Request.IsAuthenticated) { // Get the signed in user's id and create a token cache string signedInUserId = ClaimsPrincipal.Current?.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(signedInUserId)) { Flash("The user is not found in session token store. Please sign out and sign in again"); filterContext.Result = RedirectToAction("Index", "Home"); return; } SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId, HttpContext); if (tokenStore.HasData()) { // Add the user to the view bag ViewBag.User = tokenStore.GetUserDetails(); } else { // The session has lost data. This happens often // when debugging. Log out so the user can log back in Request.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); filterContext.Result = RedirectToAction("Index", "Home"); } } base.OnActionExecuting(filterContext); }
public ActionResult SignOut() { if (Request.IsAuthenticated) { var tokenStore = new SessionTokenStore(null, System.Web.HttpContext.Current, ClaimsPrincipal.Current); tokenStore.Clear(); Request.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); } return(RedirectToAction("Index", "Home")); }
public ActionResult SignOut() { if (Request.IsAuthenticated) { string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; SessionTokenStore sessionTokenStore = new SessionTokenStore(signedInUserId, HttpContext); sessionTokenStore.clear(); Request.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); } return(RedirectToAction("Index", "Home")); }
public static async Task <Uri> GetConsentUriForScopesIfNeeded(string[] scopes, string redirect) { // Combine the requested scopes with the default set of scopes // requested at sign in var combinedScopes = graphScopes.Union(scopes); // Create an MSAL client and token cache var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, ClaimsPrincipal.Current); var accounts = await idClient.GetAccountsAsync(); try { // See if there is a token in the cache that has all of the required scopes // If so, the user has already granted the permission we need var result = await idClient .AcquireTokenSilent(combinedScopes, accounts.FirstOrDefault()) .ExecuteAsync(); return(null); } catch (MsalUiRequiredException) { // This exception indicates that the user needs to consent // to one or more of the required scopes. // Save the page the user is on into the state parameter var stateParam = new Dictionary <string, string>(); stateParam.Add("state", redirect); // Build the authorization URL var uri = await idClient.GetAuthorizationRequestUrl(scopes) .WithAccount(accounts.FirstOrDefault()) .WithRedirectUri($"{redirectUri}Account/Consent") .WithExtraQueryParameters(stateParam) .ExecuteAsync(); // Add the "prompt=consent" query parameter var queryParams = HttpUtility.ParseQueryString(uri.Query); queryParams["prompt"] = "consent"; var builder = new UriBuilder(uri); builder.Query = queryParams.ToString(); return(builder.Uri); } }
public static async Task RedeemCodeForAdditionalConsent(string code) { // Create the MSAL client with a special redirect var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri($"{redirectUri}Account/Consent") .WithClientSecret(appSecret) .Build(); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, ClaimsPrincipal.Current); // Exchange the code for a token var result = await idClient .AcquireTokenByAuthorizationCode(graphScopes, code) .ExecuteAsync(); }
private async static Task <string> GetAccessTokenAsync() { var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, ClaimsPrincipal.Current); var accounts = await idClient.GetAccountsAsync(); var scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); return(result.AccessToken); }
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification) { var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; var tokenStore = new SessionTokenStore(signedInUserId, HttpContext.Current); tokenStore.Initialize(idClient.UserTokenCache); try { string[] scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenByAuthorizationCode( scopes, notification.Code).ExecuteAsync(); var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken); var cachedUser = new CachedUser() { DisplayName = userDetails.DisplayName, Email = string.IsNullOrEmpty(userDetails.Mail) ? userDetails.UserPrincipalName : userDetails.Mail, Avatar = string.Empty }; tokenStore.SaveUserDetails(cachedUser); } catch (MsalException ex) { string message = "AcquireTokenByAuthorizationCodeAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } catch (Microsoft.Graph.ServiceException ex) { string message = "GetUserDetailsAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (Request.IsAuthenticated) { string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; SessionTokenStore sessionTokenStore = new SessionTokenStore(signedInUserId, HttpContext); if (sessionTokenStore.HasData()) { ViewBag.User = sessionTokenStore.GetUserDetails(); } else { Request.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); filterContext.Result = RedirectToAction("Index", "Home"); } } base.OnActionExecuting(filterContext); }
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification) { // Get the signed in user's id and create a token cache string signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase); var idClient = new ConfidentialClientApplication( appId, redirectUri, new ClientCredential(appSecret), tokenStore.GetMsalCacheInstance(), null); try { string[] scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenByAuthorizationCodeAsync( notification.Code, scopes); var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken); var cachedUser = new CachedUser() { DisplayName = userDetails.DisplayName, Email = string.IsNullOrEmpty(userDetails.Mail) ? userDetails.UserPrincipalName : userDetails.Mail, Avatar = string.Empty, AccessToken = result.AccessToken }; tokenStore.SaveUserDetails(cachedUser); } catch (MsalException ex) { string message = "AcquireTokenByAuthorizationCodeAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } catch (Microsoft.Graph.ServiceException ex) { string message = "GetUserDetailsAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } }
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification) { notification.HandleCodeRedemption(); var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser); try { string[] scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenByAuthorizationCode( scopes, notification.Code).ExecuteAsync(); var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken); var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(result.IdToken) as JwtSecurityToken; var sid = jsonToken.Claims.First(claim => claim.Type == "sid"); tokenStore.SaveSid(sid.Value); tokenStore.SaveUserDetails(userDetails); notification.HandleCodeRedemption(null, result.IdToken); } catch (MsalException ex) { string message = "AcquireTokenByAuthorizationCodeAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } catch (Microsoft.Graph.ServiceException ex) { string message = "GetUserDetailsAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } }
public static async Task UpdateUserProfilePhotoAsync(Stream photoStream) { var graphClient = GetAuthenticatedClient(); // Update the photo await graphClient.Me.Photo.Content .Request() .PutAsync(photoStream); var tokenStore = new SessionTokenStore(null, HttpContext.Current, ClaimsPrincipal.Current); var cachedUser = tokenStore.GetUserDetails(); // Get the avatar-sized photo and save // it in the cache cachedUser.Avatar = await GetUserPhotoAsDataUriAsync(graphClient, "48x48"); tokenStore.SaveUserDetails(cachedUser); }
private static async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification) { //IConfidentialClientApplication clientApp = MsalAppBuilder. notification.HandleCodeRedemption(); var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser); try { string[] scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenByAuthorizationCode( scopes, notification.Code).ExecuteAsync(); //var userMessage = await GraphHelper.GetMeAsync(result.AccessToken); //var userSend = await GraphHelper.SendMailAsync(result.AccessToken); //var userDetails = await OutlookFW.Web.Controllers.MailController._mailAppService.GetUserDetailsAsync(result.AccessToken); //email= userDetails.Email.ToString(); accessToken = result.AccessToken; //tokenStore.SaveUserDetails(userDetails); notification.HandleCodeRedemption(null, result.IdToken); } catch (MsalException ex) { string message = "AcquireTokenByAuthorizationCodeAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } catch (Microsoft.Graph.ServiceException ex) { string message = "GetUserDetailsAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } }
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification) { var idClient = ConfidentialClientApplicationBuilder.Create(appId) .WithRedirectUri(redirectUri) .WithClientSecret(appSecret) .Build(); var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity); var tokenStore = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser); try { string[] scopes = graphScopes.Split(' '); var result = await idClient.AcquireTokenByAuthorizationCode( scopes, notification.Code).ExecuteAsync(); var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken); string profilePhoto; try { var photo = await GraphHelper.GetUserPhotoAsync(result.AccessToken); if (photo != null) { profilePhoto = "data:image/png;base64, " + Convert.ToBase64String(photo); } else { profilePhoto = null; } } catch { profilePhoto = null; } var cachedUser = new CachedUser() { DisplayName = userDetails.DisplayName, Email = userDetails.UserPrincipalName, TenantID = result.TenantId, Avatar = profilePhoto }; tokenStore.SaveUserDetails(cachedUser); } catch (MsalException ex) { string message = "AcquireTokenByAuthorizationCodeAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } catch (Microsoft.Graph.ServiceException ex) { string message = "GetUserDetailsAsync threw an exception"; notification.HandleResponse(); notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}"); } }