// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.Use(async(context, next) => { if (context.Request.IsHttps) { await next(); } else { var httpsUrl = "https://" + context.Request.Host + context.Request.Path; context.Response.Redirect(httpsUrl); } }); app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookieAuthentication(); var Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Authority, CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, SaveTokens = true, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async context => { string userId = context.JwtSecurityToken.Claims.FirstOrDefault(c => c.Type.Equals("oid")).Value; TokenCacheConfig TokenCacheConfig = new TokenCacheConfig(Configuration); AzureTableStoreTokenCache tokenCache = await AzureTableStoreTokenCache.GetTokenCacheAsync(TokenCacheConfig, userId); if (!await tokenCache.UserExists(userId)) { string userUpn = context.JwtSecurityToken.Claims.FirstOrDefault(c => c.Type.Equals("upn")).Value; string userFirstName = context.JwtSecurityToken.Claims.FirstOrDefault(c => c.Type.Equals("given_name")).Value; var sg = new SendGridAPIClient(Configuration["SENDGRID"]); Email from = new Email("*****@*****.**", "Magic Mirror"); Email to = new Email(userUpn); string subject = "Hello from Magic Mirror @ DRIVE FY17!"; Content content = new Content("text/html", " "); Mail mail = new Mail(from, subject, to, content); mail.TemplateId = "f76ceeb2-8ee5-4ff7-9b8a-a7358125b717"; mail.Personalization[0].AddSubstitution("-name-", userFirstName); var response = await sg.client.mail.send.post(requestBody: mail.Get()); } // given the authorization code var authorizationCode = context.ProtocolMessage.Code; var request = context.HttpContext.Request; var redirectUri = new Uri(context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + "/signin-oidc"); // get and verify the access token and refresh token var credential = new ClientCredential(Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authContext = new AuthenticationContext(Authority, tokenCache); var result = await authContext.AcquireTokenByAuthorizationCodeAsync(authorizationCode, redirectUri, credential, "https://graph.microsoft.com"); // serialize the per-user TokenCache var tokenBlob = tokenCache.Serialize(); // and store it in the authentication properties so that the Controller can access it context.HandleCodeRedemption(result.AccessToken, result.IdToken); } } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
private async Task ShowPersonalizedInfoPanel(Person person) { ClientCredential credential = new ClientCredential(ClientId, ClientSecret); AzureTableStoreTokenCache tokenCache = await AzureTableStoreTokenCache.GetTokenCacheAsync(new TokenCacheConfig(), person.Name); AuthenticationContext authContext = new AuthenticationContext(Authority, tokenCache); AuthenticationResult accessTokenAuthenticationResult = await authContext.AcquireTokenSilentAsync(MicrosoftGraphEndpoint, credential, new UserIdentifier(person.Name, UserIdentifierType.UniqueId)); GraphServiceClient graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( (requestMessage) => { string accessToken = accessTokenAuthenticationResult.AccessToken; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return(Task.FromResult(0)); })); User me = await graphClient.Me.Request().Select(UserParameters).GetAsync(); // Get user's unread mail count var inbox = await graphClient.Me.MailFolders.Inbox.Request().GetAsync(); var unreadMail = inbox.UnreadItemCount; if (unreadMail > 99) { unreadMail = 99; } tbMail.Text = unreadMail.ToString(); // Weather var weather = await GetCurrentWeather(); int currentTemperature = (int)weather.Temperature.Value; tbWeatherValue.Text = currentTemperature.ToString(); var icon = GetWeatherIcon(weather.Weather.Icon); WeatherImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(base.BaseUri, icon)); tbWeatherText.Text = weather.Weather.Value; List <QueryOption> options = new List <QueryOption> { new QueryOption(StartDatetimeGraphQueryOption, DateTime.UtcNow.ToString("o")), new QueryOption(EndDatetimeGraphQueryOption, DateTime.UtcNow.AddDays(1).ToString("o")) }; IUserCalendarViewCollectionPage cal = await graphClient.Me.CalendarView.Request(options).Top(1).GetAsync(); DrivingInfo drivingInfo; string displayName, displayDrive, displayNext; try { drivingInfo = await GetDrivingInfoAsync(me.City); displayDrive = string.Concat("Office ETA ", (drivingInfo.DurationTrafic / 60).ToString("F0"), "mins (", drivingInfo.Distance.ToString("F0"), "Km)"); } catch (Exception ex) { displayDrive = string.Empty; HockeyClient.Current.TrackEvent("User Driving Info - Exception", new Dictionary <string, string> { { "Message", ex.Message }, { "Stack", ex.StackTrace } }); } if (!string.IsNullOrEmpty(me.DisplayName)) { displayName = string.Concat("Hi ", me.DisplayName); } else { displayName = string.Empty; HockeyClient.Current.TrackEvent("User Display Name", new Dictionary <string, string> { { "User", me.Id } }); } if (cal.FirstOrDefault() != null) { displayNext = string.Concat("Next: ", cal.FirstOrDefault().Subject, " @ ", cal.FirstOrDefault().Location.DisplayName); } else { displayNext = string.Empty; HockeyClient.Current.TrackEvent("User Calendar", new Dictionary <string, string> { { "User", me.Id } }); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { tbName.Text = displayName; tbDrive.Text = displayDrive; tbNext.Text = displayNext; }); }