private async Task <AccessTokenResponse> GetNewToken() { var authClient = new Auth0.AuthenticationApi.AuthenticationApiClient( ConfigurationManager.AppSettings["auth0:Domain"]); return(await authClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = ConfigurationManager.AppSettings["auth0:ClientId"], ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"], Audience = $"https://{ConfigurationManager.AppSettings["auth0:Domain"]}/api/v2/" })); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Try and validate the user using var auth = new Auth0.AuthenticationApi.AuthenticationApiClient(new Uri(string.Format("https://{0}/", ConfigurationManager.AppSettings["auth0:Domain"]))); try { // Autenticate the user var authResponse = await auth.Authenticate(new AuthenticationRequest { Connection = "Username-Password-Authentication", ClientId = ConfigurationManager.AppSettings["auth0:ClientId"], Scope = "openid name email", Username = model.Email, Password = model.Password }); // Get user information from the token User user = await auth.GetTokenInfo(authResponse.IdToken); // Create a valid claims identity with the relevant claims, and sign the identity in ClaimsIdentity identity = new ClaimsIdentity(null, DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0")); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId)); identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.FullName)); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Redirect to return URL (of specified) return(RedirectToLocal(returnUrl)); } catch (Exception e) { ModelState.AddModelError("", e.Message); return(View(model)); } }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // Try and validate the user using var auth = new Auth0.AuthenticationApi.AuthenticationApiClient(new Uri(string.Format("https://{0}/", ConfigurationManager.AppSettings["auth0:Domain"]))); try { // Autenticate the user var authResponse = await auth.Authenticate(new AuthenticationRequest { Connection = "Username-Password-Authentication", ClientId = ConfigurationManager.AppSettings["auth0:ClientId"], Scope = "openid name email", Username = model.Email, Password = model.Password }); // Get user information from the token User user = await auth.GetTokenInfo(authResponse.IdToken); // Create a valid claims identity with the relevant claims, and sign the identity in ClaimsIdentity identity = new ClaimsIdentity(null, DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0")); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId)); identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.FullName)); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Redirect to return URL (of specified) return RedirectToLocal(returnUrl); } catch (Exception e) { ModelState.AddModelError("", e.Message); return View(model); } }
public void Configuration(IAppBuilder app) { // Configure Auth0 parameters string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"]; string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"]; string auth0ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"]; string auth0RedirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"]; string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:PostLogoutRedirectUri"]; const string ApiIdentifier = "{YOUR_API_IDENTIFIER}"; // Enable Kentor Cookie Saver middleware app.UseKentorOwinCookieSaver(); // Set Cookies as default authentication type app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, LoginPath = new PathString("/Account/Login") }); // Configure Auth0 authentication app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { AuthenticationType = "Auth0", Authority = $"https://{auth0Domain}", ClientId = auth0ClientId, ClientSecret = auth0ClientSecret, RedirectUri = auth0RedirectUri, PostLogoutRedirectUri = auth0PostLogoutRedirectUri, ResponseType = OpenIdConnectResponseType.CodeIdToken, // the "offline_access" scope indicates // that we want a refresh token in the response Scope = "openid profile email offline_access", TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }, Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = notification => { // this if block will add the "audience" parameter // with the identifier for which you want to get an access token // make sure to replace with your own identifier // or just delete this block if you just want an access token // for the OIDC user profile endpoint if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) { notification.ProtocolMessage.SetParameter("audience", ApiIdentifier); } if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) { var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}"; var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = notification.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } notification.Response.Redirect(logoutUri); notification.HandleResponse(); } return(Task.FromResult(0)); }, AuthorizationCodeReceived = async notification => { // The OpenIdConnectAuthentication middleware does not // automatically exchange the authorization code for a // token result, so we do it here. using (var client = new Auth0.AuthenticationApi.AuthenticationApiClient(auth0Domain)) { var tokenResult = await client.GetTokenAsync(new Auth0.AuthenticationApi.Models.AuthorizationCodeTokenRequest { ClientId = auth0ClientId, ClientSecret = auth0ClientSecret, RedirectUri = notification.RedirectUri, Code = notification.Code }); // We'll store the access token, the access token expiration // and the refresh token in the user identity (which ends // up in the session cookie). This is not the only alternative, // the tokens could be stored elsewhere, like in a database or // another type of long term storage. if (!string.IsNullOrEmpty(tokenResult.RefreshToken)) { notification.AuthenticationTicket.Identity.AddClaim(new Claim("refresh_token", tokenResult.RefreshToken)); } notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", tokenResult.AccessToken)); var accessTokenExpirationDate = DateTime.Now.AddSeconds(tokenResult.ExpiresIn); notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token_expires_at", accessTokenExpirationDate.ToString("o"))); } } } }); }
public async Task <IActionResult> ExportPdf( string postcode, double lat, double lng, int[] staticClaimIds, int[] claimIds, Industry industry, string region) { var sources = _claimService .GetSources(region) .OrderBy(a => a.Id) .ToDictionary(a => a.Id, a => a.Text); var pdfModel = new SingleViewPdfViewModel() { Postcode = postcode, Lat = lat, Lng = lng, Industry = industry, MapsUrl = await _claimService.GetPathToPostalCodeImage(postcode, region), ImageDomain = _asposeOptions.ImageUrl, Sources = sources }; if (staticClaimIds != null && staticClaimIds.Any()) { pdfModel.StaticClaims = _claimService.GetStaticClaims(staticClaimIds, region).ToList(); } if (claimIds != null && claimIds.Any()) { var claims = _claimService.GetClaims(claimIds, region); pdfModel.Claims = _claimService.PopulateValues(claims, postcode, region).ToList(); } var html = _view.Render(@"Pdf\SingleView", pdfModel); var authClient = new Auth0.AuthenticationApi.AuthenticationApiClient("mudbath.au.auth0.com"); var authReq = new AuthenticationRequest() { ClientId = _auth0Config.ClientId, Username = _auth0Config.Username, Password = _auth0Config.Password, Connection = "Username-Password-Authentication", GrantType = "password", Scope = "openid" }; var resp = await authClient.AuthenticateAsync(authReq); var httpClient = new HttpClient { BaseAddress = new Uri(_asposeOptions.BaseUrl) }; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resp.IdToken); var content = JsonConvert.SerializeObject(new { Html = html }); var httpResp = await httpClient.PostAsync( "api/pdf/generate", new StringContent(content, Encoding.UTF8, "application/json")); if (!httpResp.IsSuccessStatusCode) { var error = httpResp.Content.ReadAsStringAsync(); Console.WriteLine(error); httpResp.EnsureSuccessStatusCode(); } var pdf = await httpResp.Content.ReadAsStreamAsync(); return(File(pdf, "application/pdf", $"Export-{postcode}-{DateTime.Now.ToString("dd-MM-yyy HH:mm")}.pdf")); }
public async Task <IActionResult> ExportImage( string postcode, int[] staticClaimIds, int[] claimIds, string region) { var tileClaims = new List <TileViewModel>(); if (staticClaimIds != null && staticClaimIds.Any()) { var staticClaims = _claimService .GetStaticClaims(staticClaimIds, region) .Select(x => new TileViewModel() { Value = x.Value, ImagePath = x.ImagePath, Heading = x.Heading, FormattedText = x.ClaimText, ImageDomain = _asposeOptions.ImageUrl, SourceId = x.SourceId }) .ToList(); tileClaims.AddRange(staticClaims); } if (claimIds != null && claimIds.Any()) { var claims = _claimService.GetClaims(claimIds, region); var popClaims = _claimService .PopulateValues(claims, postcode, region) .Select(x => new TileViewModel() { Heading = x.ClaimName, Value = x.ClaimValue, ImagePath = x.ImagePath, FormattedText = x.FormattedClaimText, ImageDomain = _asposeOptions.ImageUrl, SourceId = x.SourceId }) .ToList(); tileClaims.AddRange(popClaims); } var sourceText = _claimService .GetSources(region) .Select(a => $"{a.Id}. {a.Text}") .Aggregate(new StringBuilder(), (a, b) => a.AppendFormat("{0} ", b)) .ToString() .Trim(); var htmls = tileClaims .Select(a => _view.Render(@"Image\SingleView", a)) .ToList(); var authClient = new Auth0.AuthenticationApi.AuthenticationApiClient("mudbath.au.auth0.com"); var authReq = new AuthenticationRequest() { ClientId = _auth0Config.ClientId, Username = _auth0Config.Username, Password = _auth0Config.Password, Connection = "Username-Password-Authentication", GrantType = "password", Scope = "openid" }; var resp = await authClient.AuthenticateAsync(authReq); var httpClient = new HttpClient { BaseAddress = new Uri(_asposeOptions.BaseUrl) }; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resp.IdToken); var content = JsonConvert.SerializeObject(new { Htmls = htmls, Width = 360 }); var httpResp = await httpClient.PostAsync( "api/image/generate", new StringContent(content, Encoding.UTF8, "application/json")); if (!httpResp.IsSuccessStatusCode) { var error = httpResp.Content.ReadAsStringAsync(); Console.WriteLine(error); httpResp.EnsureSuccessStatusCode(); } var images = await httpResp.Content.ReadAsStringAsync(); var imagesByteList = JsonConvert.DeserializeObject <List <byte[]> >(images); var zip = CreateZip(imagesByteList, sourceText); var fileName = $"image-export-{postcode}-{DateTime.Now.ToString("dd-MM-yyy HH:mm")}.zip"; return(File(zip, "application/zip", fileName)); }
public async Task <IActionResult> GeneratePdf(string[] postcodes, string[] svgGuids, Industry industry, string region) { var sources = _claimService .GetSources(region) .OrderBy(a => a.Id) .ToDictionary(a => a.Id, a => a.Text); var pdfModel = new ComparePdfViewModel() { Industry = industry, Sources = sources }; var populatedPostcodes = new List <ComparisonPostcode>(); foreach (var code in postcodes) { populatedPostcodes.Add(_claimService.ComparePostcode(code, industry, region)); } pdfModel.Postcodes = populatedPostcodes; pdfModel.TotalCards = populatedPostcodes.Sum(x => x.Cards); pdfModel.TotalTransactions = populatedPostcodes.Sum(x => x.Transactions); pdfModel.TotalMerchantSpend = populatedPostcodes.Sum(x => x.MerchantSpend); pdfModel.ImageDomain = _asposeOptions.ImageUrl; var cardSvgPath = Path.Combine(_env.WebRootPath, "svgs", svgGuids[0] + ".svg"); var transSvgPath = Path.Combine(_env.WebRootPath, "svgs", svgGuids[1] + ".svg"); var spendSvgPath = Path.Combine(_env.WebRootPath, "svgs", svgGuids[2] + ".svg"); pdfModel.CardSvg = System.IO.File.ReadAllText(cardSvgPath); pdfModel.TransSvg = System.IO.File.ReadAllText(transSvgPath); pdfModel.SpendSvg = System.IO.File.ReadAllText(spendSvgPath); var html = _view.Render(@"Pdf\CompareView", pdfModel); var authClient = new Auth0.AuthenticationApi.AuthenticationApiClient("mudbath.au.auth0.com"); var authReq = new AuthenticationRequest() { ClientId = _auth0Config.ClientId, Username = _auth0Config.Username, Password = _auth0Config.Password, Connection = "Username-Password-Authentication", GrantType = "password", Scope = "openid" }; var resp = await authClient.AuthenticateAsync(authReq); var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(this._asposeOptions.BaseUrl); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resp.IdToken); var content = JsonConvert.SerializeObject(new { Html = html }); var httpResp = await httpClient.PostAsync("api/pdf/generate", new StringContent(content, Encoding.UTF8, "application/json")); if (!httpResp.IsSuccessStatusCode) { var error = httpResp.Content.ReadAsStringAsync(); Console.WriteLine(error); httpResp.EnsureSuccessStatusCode(); } var pdf = await httpResp.Content.ReadAsStreamAsync(); System.IO.File.Delete(cardSvgPath); System.IO.File.Delete(transSvgPath); System.IO.File.Delete(spendSvgPath); return(File(pdf, "application/pdf", $"comparison-{DateTime.Now.ToString("dd-MM-yyy HH:mm")}.pdf")); }