/// <summary> /// Redeems the authorization code by calling AcquireTokenByAuthorizationCodeAsync in order to ensure /// that the cache has a token for the signed-in user, which will then enable the controllers (like the /// TodoController, to call AcquireTokenSilentAsync successfully. /// </summary> private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context) { // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API string userObjectId = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; var code = context.ProtocolMessage.Code; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(azureAdOptions.ClientId, azureAdOptions.Authority, azureAdOptions.RedirectUri, new ClientCredential(azureAdOptions.ClientSecret), userTokenCache, null); try { var scopes = azureAdOptions.ApiScopes.Split(' '); var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); //AcquireTokenSilentAsync(scopes, cca.Users.FirstOrDefault(), azureAdOptions.Authority, false); context.HandleCodeRedemption(result.AccessToken, result.IdToken); } catch (Exception ex) { //TODO: Handle throw; } // Notify the OIDC middleware that we already took care of code redemption. }
public async Task <ActionResult> SendMail() { // try to get token silently string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null); var accounts = await cca.GetAccountsAsync(); if (accounts.Any()) { string[] scopes = { "Mail.Send" }; try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, accounts.First()); } catch (MsalUiRequiredException) { try {// when failing, manufacture the URL and assign it string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url); ViewBag.AuthorizationRequest = authReqUrl; } catch (Exception ee) { Response.Write(ee.Message); } } } else { } return(View()); }
public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context) { var clientCredential = new ClientCredential(context.Options.ClientSecret); var userId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; var userTokenCache = new MSALSessionCache(userId, context.HttpContext).GetMsalCacheInstance(); var confidentialClientApplication = new ConfidentialClientApplication( context.Options.ClientId, context.Options.Authority, $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}", clientCredential, userTokenCache, null); try { var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCodeAsync( context.ProtocolMessage.Code, new[] { "https://contoso.onmicrosoft.com/api/user_impersonation" }); context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken); } catch (Exception ex) { // TODO: Handle. throw; } }
public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context) { // Use MSAL to swap the code for an access token // Extract the code from the response notification var code = context.ProtocolMessage.Code; foreach (var claim in context.Ticket.Principal.Claims) { System.Console.WriteLine(claim.Type + "-->" + claim.Value); } string signedInUserID = context.Ticket.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' ')); context.HandleCodeRedemption(result.AccessToken, result.IdToken); } catch (Exception ex) { //TODO: Handle throw; } }
public async Task <ActionResult> SendMail() { // try to get token silently string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; MSALSessionCache theCache = new MSALSessionCache(signedInUserID, this.HttpContext); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), theCache); string[] scopes = { "Mail.Send" }; try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes); } catch (MsalSilentTokenAcquisitionException) { try {// when failing, manufacture the URL and assign it string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url); ViewBag.AuthorizationRequest = authReqUrl; } catch (Exception ee) { } } return(View()); }
public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context) { // Use MSAL to swap the code for an access token // Extract the code from the response notification var code = context.ProtocolMessage.Code; string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; string displayName = context.Principal.FindFirst("Name").Value; string email = context.Principal.FindFirst("Emails").Value; string country = String.Empty; if (context.Principal.FindFirst("Country") != null) { country = context.Principal.FindFirst("Country").Value; } TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' ')); context.HandleCodeRedemption(result.AccessToken, result.IdToken); } catch (Exception ex) { //TODO: Handle throw; } }
protected override string GetBearerToken() { string accessToken = (HttpContext.Current.User.Identity as ClaimsIdentity)?.FindFirst("AccessToken").Value; if (!string.IsNullOrEmpty(accessToken)) { return(accessToken); } var signedInUserId = (HttpContext.Current.User.Identity as ClaimsIdentity)?.FindFirst("userId").Value; var cache = new MSALSessionCache(signedInUserId, HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); var clientCred = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientSecret"]); var context = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, ConfigurationManager.AppSettings["ida:RedirectUri"], clientCred, cache, null); var user = context.Users.FirstOrDefault(); if (user == null) {//Clear cookies and notify error handler that cache is corrupted HttpContext.Current.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); throw new ServerException(new ErrorDetail { Message = "Invalid token cache" }, HttpStatusCode.Unauthorized); } var token = Task.Run(async() => await context.AcquireTokenSilentAsync(new[] { ConfigurationManager.AppSettings["api:scope"] }, user, Startup.Authority, false)).Result; return(token.AccessToken); }
// GET: Admin public async Task <ActionResult> Index() { // try to get token silently string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache theCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), theCache, null); string[] scopes = adminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First()); } catch (Exception) { try {// when failing, manufacture the URL and assign it string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url); ViewBag.AuthorizationRequest = authReqUrl; } catch (Exception ee) { } } return(View("Admin")); }
public async Task <ActionResult> CallAPI() { string responseString = ""; try { // Retrieve the token with the specified scopes var scope = new string[] { Startup.ReadTasksScope }; string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null); var user = cca.Users.FirstOrDefault(); if (user == null) { HttpContext.GetOwinContext().Authentication.Challenge(); return(null); //throw new Exception("The User is NULL. Please clear your cookies and try again. Specifically delete cookies for 'login.microsoftonline.com'. See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9"); } AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, user, Startup.Authority, false); var myApi = ConfigurationManager.AppSettings["api:myApiV3Url"]; var myApiProfileUrl = $"{myApi}my/profile"; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, myApiProfileUrl); // Add token to the Authorization header and make the request request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // Handle the response switch (response.StatusCode) { case HttpStatusCode.OK: responseString = await response.Content.ReadAsStringAsync(); break; case HttpStatusCode.Unauthorized: responseString = $"Please sign in again. {response.ReasonPhrase}"; break; default: responseString = $"Error calling API. StatusCode=${response.StatusCode}"; break; } } catch (Exception ex) { responseString = $"Error calling API: {ex.Message}"; //return ErrorAction("Error reading to do list: " + ex.Message); } ViewData["Payload"] = $"{responseString}"; return(View()); }
// Gets an access token and its expiration date. First tries to get the token from the token cache. public async Task <string> GetUserAccessTokenAsync() { // Initialize the cache. HttpContextBase context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase; tokenCache = new MSALSessionCache( ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value, context).GetMsalCacheInstance(); //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache if (!redirectUri.EndsWith("/")) { redirectUri = redirectUri + "/"; } string[] segments = context.Request.Path.Split(new char[] { '/' }); string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"); ClientCredential clientCred = new ClientCredential(appSecret); ConfidentialClientApplication cca = new ConfidentialClientApplication(appId, Authority, redirectUri + segments[1], clientCred, tokenCache, null); bool?isAdmin = HttpContext.Current.Session["IsAdmin"] as bool?; string allScopes = nonAdminScopes; if (isAdmin.GetValueOrDefault()) { allScopes += " " + adminScopes; } string[] scopes = allScopes.Split(new char[] { ' ' }); try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First()); return(result.AccessToken); } // Unable to retrieve the access token silently. catch (Exception) { HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( new AuthenticationProperties() { RedirectUri = redirectUri + segments[1] }, OpenIdConnectAuthenticationDefaults.AuthenticationType); throw new ServiceException( new Error { Code = GraphErrorCode.AuthenticationFailure.ToString(), Message = Resource.Error_AuthChallengeNeeded, }); } }
private async Task <AuthenticationResult> ObtainTokenFromAzureAdAsync(string signedInUserID, string userObjectID) { var scopes = _azureAdOptions.ApiScopes.Split(' '); TokenCache userTokenCache = new MSALSessionCache(signedInUserID, _httpContext).GetMsalCacheInstance(); // Using ADAL.Net, get a bearer token to access the TodoListService ConfidentialClientApplication cca = new ConfidentialClientApplication(_azureAdOptions.ClientId, _azureAdOptions.Authority, _azureAdOptions.RedirectUri, new ClientCredential(_azureAdOptions.ClientSecret), userTokenCache, null); var result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.FirstOrDefault(), _azureAdOptions.Authority, false); return(result); }
private async Task <AuthenticationResult> ObtainTokenFromAzureAdB2CAsync(string signedInUserID) { // Retrieve the token with the specified scopes var scopes = _azureAdB2COptions.ApiScopes.Split(' '); TokenCache userTokenCache = new MSALSessionCache(signedInUserID, _httpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(_azureAdB2COptions.ClientId, _azureAdB2COptions.Authority, _azureAdB2COptions.RedirectUri, new ClientCredential(_azureAdB2COptions.ClientSecret), userTokenCache, null); var result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.FirstOrDefault(), _azureAdB2COptions.Authority, false); return(result); }
public async Task <ActionResult> DeleteSubscription() { string subscriptionsEndpoint = "https://graph.microsoft.com/v1.0/subscriptions/"; string subscriptionId = (string)Session["SubscriptionId"]; // Build the request. HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, subscriptionsEndpoint + subscriptionId); // try to get token silently string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null); var accounts = await cca.GetAccountsAsync(); if (accounts.Any()) { string[] scopes = { "Mail.Read" }; try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, accounts.First()); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // Send the `DELETE subscriptions/id` request. HttpResponseMessage response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { return(RedirectToAction("Index", "Error", new { message = response.StatusCode, debug = response.Content.ReadAsStringAsync() })); } } catch (MsalUiRequiredException) { try {// when failing, manufacture the URL and assign it string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url); ViewBag.AuthorizationRequest = authReqUrl; } catch (Exception ee) { Response.Write(ee.Message); } } } else { } return(RedirectToAction("SignOut", "Account")); }
/* * Callback function when an authorization code is received */ private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Extract the code from the response notification var code = notification.Code; var signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; var userTokenCache = new MSALSessionCache(signedInUserId, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase) .GetMsalCacheInstance(); var cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null); var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes); }
public async Task <ActionResult> Create(string description) { try { // Retrieve the token with the specified scopes string accessToken = null; try { var scope = new string[] { Startup.WriteTasksScope }; string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null); AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), Startup.Authority, false); accessToken = result.AccessToken; } catch (Exception) { //Require interactive signin } // Set the content var httpContent = new[] { new KeyValuePair <string, string>("Text", description) }; // Create the request HttpClient client = new HttpClient(); HttpContent content = new FormUrlEncodedContent(httpContent); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); // Handle the response switch (response.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.NoContent: case HttpStatusCode.Created: return(new RedirectResult("/Tasks")); case HttpStatusCode.Unauthorized: return(ErrorAction("Please sign in again. " + response.ReasonPhrase)); default: return(ErrorAction("Error. Status code = " + response.StatusCode)); } } catch (Exception ex) { return(ErrorAction("Error writing to list: " + ex.Message)); } }
public async Task <IActionResult> Api() { string responseString = ""; try { // Retrieve the token with the specified scopes var scope = AzureAdB2COptions.ApiScopes.Split(' '); string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null); AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false); Validate(result.AccessToken); HttpClient client = new HttpClient(); string GateWayUrl = "https://tenant3.winshuttleonline.net/api/users"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, GateWayUrl); // Add token to the Authorization header and make the request request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // Handle the response switch (response.StatusCode) { case HttpStatusCode.OK: responseString = await response.Content.ReadAsStringAsync(); break; case HttpStatusCode.Unauthorized: responseString = $"Please sign in again. {response.ReasonPhrase}"; break; default: responseString = $"Error calling API. StatusCode=${response.StatusCode}"; break; } } catch (MsalUiRequiredException ex) { responseString = $"Session has expired. Please sign in again. {ex.Message}"; } catch (Exception ex) { responseString = $"Error calling API: {ex.Message}"; } ViewData["Payload"] = $"{responseString}"; return(View()); }
public static ConfidentialClientApplication GetAppBuilder(string signedInUserId, HttpContextBase httpContextBase) { TokenCache userTokenCache = new MSALSessionCache(signedInUserId, httpContextBase).GetMsalCacheInstance(); ClientCredential clientCredential = new ClientCredential(AuthenticationConfig.appKey); ConfidentialClientApplication confidentialClientApplication = new ConfidentialClientApplication(AuthenticationConfig.clientId, AuthenticationConfig.authority, AuthenticationConfig.redirectUri, clientCredential, userTokenCache, null); return(confidentialClientApplication); }
public async Task <ActionResult> Used() { var ret = new UsedInsights(); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/me/insights/used"); // try to get token silently string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null); var accounts = await cca.GetAccountsAsync(); if (accounts.Any()) { string[] scopes = { "Sites.Read.All" }; try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, accounts.First()); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var responseBody = await response.Content.ReadAsStringAsync(); ret = JsonConvert.DeserializeObject <UsedInsights>(responseBody); ViewBag.AuthorizationRequest = null; } } catch (MsalUiRequiredException) { try {// when failing, manufacture the URL and assign it string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url); ViewBag.AuthorizationRequest = authReqUrl; } catch (Exception ee) { Response.Write(ee.Message); } } } else { } return(View(ret)); }
private async Task <string> AcquireToken(string[] scopes) { string signedInUserID = User.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication( Startup.Configuration["Authentication:AzureAdB2C:ClientId"], string.Format("https://login.microsoftonline.com/tfp/{0}/{1}", Startup.Configuration["Authentication:AzureAdB2C:TenantName"], Startup.Configuration["Authentication:AzureAdB2C:SignInPolicyName"]), Startup.Configuration["Authentication:AzureAdB2C:CallbackPath"], new ClientCredential(Startup.Configuration["Authentication:AzureAdB2C:ClientSecret"]), userTokenCache, null); AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.FirstOrDefault()); return(result.AccessToken); }
public override async Task Invoke(IOwinContext context) { string code = context.Request.Query["code"]; if (code != null) { //extract state string state = HttpUtility.UrlDecode(context.Request.Query["state"]); string session_state = context.Request.Query["session_state"]; string signedInUserID = context.Authentication.User.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value; HttpContextBase hcb = context.Environment["System.Web.HttpContextBase"] as HttpContextBase; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, hcb).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(options.ClientId, options.RedirectUri, new ClientCredential(options.ClientSecret), userTokenCache, null); //validate state CodeRedemptionData crd = OAuth2RequestManager.ValidateState(state, hcb); if (crd != null) { //If Valid redeem code try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, crd.Scopes); } catch (Exception ex) { context.Response.Write(ex.Message); } //redirect to original requestor context.Response.StatusCode = 302; context.Response.Set("Location", crd.RequestOriginatorUrl); } else { context.Response.StatusCode = 302; context.Response.Set("Location", "/Error?message" + "code_redeem_failed"); } } else { await this.Next.Invoke(context); } }
/* * Callback function when an authorization code is received. */ private static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Extract the code from the response notification var code = notification.Code; var authorizationCodeReceived = new AuthorizationCodeReceivedMessage() { SignedInUserNameIdentifier = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value }; _oidcNotificationHandlerService.OnAuthorizationCodeReceived(authorizationCodeReceived); var userTokenCache = new MSALSessionCache( authorizationCodeReceived.SignedInUserNameIdentifier, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase ).GetMsalCacheInstance(); // TokenCache appTokenCache = null; var cca = new ConfidentialClientApplication( _ib2COidcConfidentialClientSettingsConfiguration.ClientId, _ib2COidcConfidentialClientSettingsConfiguration.AuthorityUri, // "https://login.microsoftonline.com/tfp/{tenantAuthorityName}/{defaultPolicyId}/v2.0/.well-known/openid-configuration" _ib2COidcConfidentialClientSettingsConfiguration.ClientRedirectUri, // eg: "https://localhost:44311" new ClientCredential(_ib2COidcConfidentialClientSettingsConfiguration.ClientSecret), userTokenCache, null); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, _fullyQualifiedScopesRequiredByTargetApi); // this is actually wrong //if (result.Scopes != null && result.Scopes.Any()) //{ // notification.AuthenticationTicket.Identity.AddClaim(new Claim(Infrastructure.Constants.IDA.ClaimTitles.ScopeElementId, string.Join(" ", result.Scopes).TrimEnd())); //} } catch (Exception ex) { Console.Write(ex.Message); throw; } }
private async Task OnAuthorization(AuthorizationCodeReceivedNotification context) { var code = context.Code; string signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null); string[] scopes = { "Mail.Read" }; try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); } catch (Exception ex) { context.Response.Write(ex.Message); } }
// GET: Makes a call to the API and retrieves the list of tasks public async Task <ActionResult> Index() { try { // Retrieve the token with the specified scopes var scope = new string[] { Startup.ReadTasksScope }; string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null); var user = cca.Users.FirstOrDefault(); if (user == null) { throw new Exception("The User is NULL. Please clear your cookies and try again. Specifically delete cookies for 'login.microsoftonline.com'. See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9"); } AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, user, Startup.Authority, false); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint); // Add token to the Authorization header and make the request request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // Handle the response switch (response.StatusCode) { case HttpStatusCode.OK: String responseString = await response.Content.ReadAsStringAsync(); JArray tasks = JArray.Parse(responseString); ViewBag.Tasks = tasks; return(View()); case HttpStatusCode.Unauthorized: return(ErrorAction("Please sign in again. " + response.ReasonPhrase)); default: return(ErrorAction("Error. Status code = " + response.StatusCode)); } } catch (Exception ex) { return(ErrorAction("Error reading to do list: " + ex.Message)); } }
private async Task <AuthenticationResult> GetAuthResultAsync() { // Retrieve the token with the specified scopes string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, authority, redirectUri, new ClientCredential(clientSecret), userTokenCache, null); //var user = cca.Users.FirstOrDefault(); var user = cca.GetAccountsAsync().Result.FirstOrDefault(); if (user == null) { throw new Exception("The User is NULL. Please clear your cookies and try again."); } return(await cca.AcquireTokenSilentAsync(scope, user, authority, false)); }
/// <summary> /// Retrieves an access token for the specified scopes. /// </summary> private async Task <string> GetAccessTokenAsync(params string[] scopes) { string signedInUserID = User.GetId(); TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null); var user = cca.Users.FirstOrDefault(); if (user == null) { throw new Exception("The User is NULL. Please clear your cookies and try again. Specifically delete cookies for 'login.microsoftonline.com'. See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9"); } AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, user, Startup.Authority, false); return(result.AccessToken); }
private async Task OnAuthorization(AuthorizationCodeReceivedNotification context) { var code = context.Code; string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"); string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential clientCred = new ClientCredential(appKey); TokenCache tokenCache = new MSALSessionCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, Authority, redirectUri, clientCred, tokenCache, null); try { string[] scopes = { "Mail.Read" }; AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); } catch (Exception eee) { } }
private async Task OnAuthroizationCodeReceivedAsync(AuthorizationCodeReceivedContext context) { var code = context.ProtocolMessage.Code; string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(_azureOptions.ClientId, _azureOptions.Authority, "https://localhost:44337/" + $"{_azureOptions.CallbackPath}", new ClientCredential(_azureOptions.ClientSecret), userTokenCache, null); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, _azureOptions.ApiScopes.Split(' ')); context.HandleCodeRedemption(result.AccessToken, result.IdToken); } catch (Exception ex) { throw; } }
/// <summary> /// Retrieves the cached access token for the WebAPI. If an access token cannot be found in the /// cache, return an empty access token. /// </summary> /// <returns>WebAPI access token. Empty if a cached access token cannot be found.</returns> private async Task <string> GetAPIAccessToken() { string accessToken = string.Empty; // The cache is built using the signed in user's identity so we must retrieve their name identifier // from the claims collection string signedInUserID = User.FindFirst(ClaimTypes.NameIdentifier).Value; // Build the identifier for the token issuing authority. Values are retrieved from configuration. // Ex. https://login.microsoftonline.com/tfp/{your B2C tenant}.onmicrosoft.com/{your B2C sign-up signin-in policy name}/v2.0 //string authority = $"{_configuration.GetValue<string>("AzureADB2C:Instance")}/{_configuration.GetValue<string>("AzureADB2C:Domain")}/{_configuration.GetValue<string>("AzureADB2C:SignUpSignInPolicyId")}/v2.0"; string authority = $"{_configuration.GetValue<string>("AzureADB2C:Instance")}tfp/{_configuration.GetValue<string>("AzureADB2C:Domain")}/{_configuration.GetValue<string>("AzureADB2C:SignUpSignInPolicyId")}"; // Build the redirect Uri // Ex. https://localhost:44340/signin-oidc string redirectUri = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, _configuration.GetValue <string>("AzureADB2C:CallbackPath")); // Reconstruct the token cache based on the signed in User ID and the current HttpContext TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance(); // Create an instance of the ConfidentialClientApplication to retrieve the access token from the cache using // the authority, redirectUri, the token cache and the client ID and client secret of the web // application (from configuration) ConfidentialClientApplication cca = new ConfidentialClientApplication(_configuration.GetValue <string>("AzureADB2C:ClientId"), authority, redirectUri, new ClientCredential(_configuration.GetValue <string>("AzureADB2C:ClientSecret")), userTokenCache, null); // Retrieve the cached access token var accounts = await cca.GetAccountsAsync(); try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(_configuration.GetValue <string>("AzureADB2C:ApiScopes").Split(' '), accounts.FirstOrDefault(), authority, false); accessToken = result.AccessToken; } catch (Exception) { // The token was not found in the cache, force a sign out of the user // so they must re-authenticate await HttpContext.SignOutAsync(); } return(accessToken); }
/* * Callback function when an authorization code is received */ private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Extract the code from the response notification var code = notification.Code; //string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; string signedInUserID = notification.AuthenticationTicket.Identity.Claims.First(c => c.Type == "userId").Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes); } catch (Exception ex) { //TODO: Handle throw; } }
/* * Callback function when an authorization code is received */ private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Extract the code from the response notification var code = notification.Code; string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); }