public void SignOut() { // Remove all cache entries for this user and send an OpenID Connect sign-out request. TokenCacheUtils.RemoveAllFromCache(); HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { Client_Id = clientId, Authority = authority, Post_Logout_Redirect_Uri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. // AccessCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); AuthenticationContext authContext = new AuthenticationContext(authority); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); // Cache the access token and refresh token TokenCacheUtils.SaveAccessTokenInCache(graphResourceId, result.AccessToken, (result.ExpiresOn.AddMinutes(-5)).ToString()); TokenCacheUtils.SaveRefreshTokenInCache(result.RefreshToken); return(Task.FromResult(0)); } } }); }
public ActionResult Edit([Bind(Include = "ObjectId,UserPrincipalName,DisplayName,City,Department")] User user) { string accessToken = null; string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; if (tenantId != null) { accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, graphResourceId); } if (accessToken == null) { // // If refresh is set to true, the user has clicked the link to be authorized again. // if (Request.QueryString["reauth"] == "True") { // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } try { // TODO: Add update logic here CallContext currentCallContext = new CallContext( accessToken, Guid.NewGuid(), graphApiVersion); GraphConnection graphConnection = new GraphConnection(currentCallContext); graphConnection.Update(user); return(RedirectToAction("Index")); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View()); } }
/// <summary> /// Gets a list of <see cref="Group"/> objects that a given <see cref="User"/> is member of. /// </summary> /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param> /// <returns>A view with the list of <see cref="Group"/> objects.</returns> public ActionResult GetGroups(string objectId) { string accessToken = null; string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; if (tenantId != null) { accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, graphResourceId); } if (accessToken == null) { // // If refresh is set to true, the user has clicked the link to be authorized again. // if (Request.QueryString["reauth"] == "True") { // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } CallContext currentCallContext = new CallContext( accessToken, Guid.NewGuid(), graphApiVersion); GraphConnection graphConnection = new GraphConnection(currentCallContext); IList <string> groupIds = graphConnection.GetMemberGroups(new User() { ObjectId = objectId }, false); return(View(groupIds)); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { Client_Id = ClientId, Authority = _authority, Post_Logout_Redirect_Uri = PostLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications { // // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. // AccessCodeReceived = context => { var code = context.Code; var credential = new ClientCredential(ClientId, AppKey); var authContext = new AuthenticationContext(_authority); var result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, GraphResourceId); // Cache the access token and refresh token TokenCacheUtils.SaveAccessTokenInCache(GraphResourceId, result.AccessToken, (result.ExpiresOn.AddMinutes(-5)).ToString()); TokenCacheUtils.SaveRefreshTokenInCache(result.RefreshToken); return(Task.FromResult(0)); } } }); }
// // GET: /UserProfile/ public async Task <ActionResult> Index() { // // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API. // UserProfile profile; string accessToken = null; string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; if (tenantId != null) { accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, _graphResourceId); } // // If the user doesn't have an access token, they need to re-authorize. // if (accessToken == null) { // // If refresh is set to true, the user has clicked the link to be authorized again. // if (Request.QueryString["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // profile = new UserProfile { DisplayName = " ", GivenName = " ", Surname = " " }; ViewBag.ErrorMessage = "AuthorizationRequired"; return(View(profile)); } // // Call the Graph API and retrieve the user's profile. // var requestUrl = String.Format( CultureInfo.InvariantCulture, _graphUserUrl, HttpUtility.UrlEncode(tenantId)); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await client.SendAsync(request); // // Return the user's profile in the view. // if (response.IsSuccessStatusCode) { var responseString = await response.Content.ReadAsStringAsync(); profile = JsonConvert.DeserializeObject <UserProfile>(responseString); } else { // // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again. // TokenCacheUtils.RemoveAccessTokenFromCache(_graphResourceId); profile = new UserProfile { DisplayName = " ", GivenName = " ", Surname = " " }; ViewBag.ErrorMessage = "UnexpectedError"; } return(View(profile)); }
// // GET: /TodoList/ public async Task <ActionResult> Index() { // // Retrieve the user's tenantID and access token since they are parameters used to call the To Do service. // string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; string accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, todoListResourceId); List <TodoItem> itemList = new List <TodoItem>(); // // If the user doesn't have an access token, they need to re-authorize. // if (accessToken == null) { // // If refresh is set to true, the user has clicked the link to be sent to be authorized again. // if (Request.QueryString["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // TodoItem newItem = new TodoItem(); newItem.Title = "(Sign-in required to view to do list.)"; itemList.Add(newItem); ViewBag.ErrorMessage = "AuthorizationRequired"; return(View(itemList)); } // // Retrieve the user's To Do List. // HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "/api/todolist"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); // // Return the To Do List in the view. // if (response.IsSuccessStatusCode) { List <Dictionary <String, String> > responseElements = new List <Dictionary <String, String> >(); JsonSerializerSettings settings = new JsonSerializerSettings(); String responseString = await response.Content.ReadAsStringAsync(); responseElements = JsonConvert.DeserializeObject <List <Dictionary <String, String> > >(responseString, settings); foreach (Dictionary <String, String> responseElement in responseElements) { TodoItem newItem = new TodoItem(); newItem.Title = responseElement["Title"]; newItem.Owner = responseElement["Owner"]; itemList.Add(newItem); } return(View(itemList)); } else { // // If the call failed with access denied, then drop the current access token from the cache, // and show the user an error indicating they might need to sign-in again. // if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { TokenCacheUtils.RemoveAccessTokenFromCache(todoListResourceId); ViewBag.ErrorMessage = "UnexpectedError"; TodoItem newItem = new TodoItem(); newItem.Title = "(No items in list)"; itemList.Add(newItem); return(View(itemList)); } } // // If the call failed for any other reason, show the user an error. // return(View("Error")); }
public async Task <ActionResult> Index(string item) { if (ModelState.IsValid) { // // Retrieve the user's tenantID and access token since they are parameters used to call the To Do service. // string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; string accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, todoListResourceId); List <TodoItem> itemList = new List <TodoItem>(); // // If the user doesn't have an access token, they need to re-authorize. // if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // TodoItem newItem = new TodoItem(); newItem.Title = "(No items in list)"; itemList.Add(newItem); ViewBag.ErrorMessage = "AuthorizationRequired"; return(View(itemList)); } // Forms encode todo item, to POST to the todo list web api. HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", item) }); // // Add the item to user's To Do List. // HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, todoListBaseAddress + "/api/todolist"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); // // Return the To Do List in the view. // if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else { // // If the call failed with access denied, then drop the current access token from the cache, // and show the user an error indicating they might need to sign-in again. // if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { TokenCacheUtils.RemoveAccessTokenFromCache(todoListResourceId); ViewBag.ErrorMessage = "UnexpectedError"; TodoItem newItem = new TodoItem(); newItem.Title = "(No items in list)"; itemList.Add(newItem); return(View(newItem)); } } // // If the call failed for any other reason, show the user an error. // return(View("Error")); } return(View("Error")); }