public AccountService(ApplicationDbContext context, UserManager <User> userManager, IEmailSenderHelper emailSenderHelper, IJWTHelper jwtHelper) : base(context) { _userManager = userManager; _emailSenderHelper = emailSenderHelper; _jwtHelper = jwtHelper; }
public DataStoreProvider(IJWTHelper _myJWTHelper, IAmazonDynamoDB client) { this.Client = client; this.context = new DynamoDBContext(this.Client); dataStoreTable = Table.LoadTable(this.Client, "BankServer_UserData"); this.myJWTHelper = _myJWTHelper; }
public ApiController(IConfiguration configuration, ICookieHelper cookieHelper, IJWTHelper JWTHelper, ICryptoHelper cryptoHelper) { _configuration = configuration; _cookieHelper = cookieHelper; _JWTHelper = JWTHelper; _cryptoHelper = cryptoHelper; }
public async Task Invoke(HttpContext context) { try { IHeaderDictionary headers = context.Request.Headers; ICookieHelper _cookieHelper = context.GetInstanceFromContext <ICookieHelper>(); IJWTHelper _JWTHelper = context.GetInstanceFromContext <IJWTHelper>(); ICryptoHelper _cryptoHelper = context.GetInstanceFromContext <ICryptoHelper>(); string cookieName = _cookieHelper.GetCookieName(); if (!_cookieHelper.isCookieDeleted(cookieName)) { string updatedToken = _JWTHelper.updateJWTToken(); string encryptedToken = _cryptoHelper.encrypt(updatedToken); _cookieHelper.UpdateCookie(encryptedToken); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { await _next.Invoke(context); } }
public async Task Invoke(HttpContext context) { try { IHeaderDictionary headers = context.Request.Headers; ICookieHelper _cookieHelper = context.GetInstanceFromContext <ICookieHelper>(); IJWTHelper _JWTHelper = context.GetInstanceFromContext <IJWTHelper>(); ICryptoHelper _cryptoHelper = context.GetInstanceFromContext <ICryptoHelper>(); string cookie = _cookieHelper.GetCookie(_cookieHelper.GetCookieName()); // Get JWT from request header. string hdrJWT = _JWTHelper.getBearerHeaderValue(headers); // If header doesn't have a JWT but the cookie does, add the cookie's JWT to the header. if (String.IsNullOrEmpty(hdrJWT) && !String.IsNullOrEmpty(cookie)) { string decryptedJWTToken = _cryptoHelper.decrypt(cookie); _JWTHelper.setClaimsFromCookie(decryptedJWTToken); string bearerToken = string.Format("Bearer {0}", cookie); headers.SetCommaSeparatedValues("Authorization", bearerToken); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { await _next.Invoke(context); } }
public UsersController( IUserService userService, IOptions <AppSettings> appSettings, ILogger <UsersController> logger, IJWTHelper jwtHelper) { _userService = userService; _appSettings = appSettings; _logger = logger; _jwtHelper = jwtHelper; }
public ProxyHelper(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _config = serviceProvider.GetInstance <IConfiguration>(); _JWTHelper = serviceProvider.GetInstance <IJWTHelper>(); if (_config != null) { _proxyPath = _config["APIProxySettings:proxyPath"]; _apiUrlQueryStringKey = _config["APIProxySettings:apiUrlQueryStringKey"]; int.TryParse(_config["APIProxySettings:bufferLengthInKB"], out _bufferLengthInKB); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; options.Events = new JwtBearerEvents { // Decrypt the JWT so it can be processed by Authorize logic. OnMessageReceived = context => { string jwt = String.Empty; string hdrJWT = String.Empty; ICryptoHelper _cryptoHelper = context.HttpContext.GetInstanceFromContext <ICryptoHelper>(); IJWTHelper _JWTHelper = context.HttpContext.GetInstanceFromContext <IJWTHelper>(); try { hdrJWT = _JWTHelper.getBearerHeaderValue(context.Request.Headers); jwt = _cryptoHelper.decrypt(hdrJWT); context.Token = jwt; } catch (Exception ex) { string msg = $"ERROR: Missing or invalid JWT. EXCEPTION: {ex.Message} JWT: {hdrJWT} DECRYPTED: {jwt}"; Console.WriteLine("USER AUTHENTICATION", "Startup.cs", "ConfigureServices.OnMessageReceived", msg, ex); } return(Task.FromResult(0)); }, // On valid token received, this fires. Useful for debugging purposes. OnTokenValidated = context => { string plainTextJWT = context.SecurityToken.ToString(); return(Task.FromResult(0)); }, // On authentication failures, redirect to the public login page OnChallenge = context => { ICryptoHelper _cryptoHelper = context.HttpContext.GetInstanceFromContext <ICryptoHelper>(); IJWTHelper _JWTHelper = context.HttpContext.GetInstanceFromContext <IJWTHelper>(); // If no path was requested, get the default landing page. Otherwise // use the requested path ensuring the correct context root is included. PathString currenturi = context.Request.Path == null ? new PathString(Configuration["AppSettings:homePageUrl"]) : new PathString(Configuration["AppSettings:appRootPath"] + context.Request.Path); // Pass the originally requested page as a querystring parm preserving its querystring if present string q = context.HttpContext.Request.QueryString.HasValue ? WebUtility.UrlEncode(context.HttpContext.Request.QueryString.ToString()) : String.Empty; string redirectUrl = Configuration["AppSettings:loginUrl"] + QueryString.Create("ReturnUrl", currenturi) + q; // Save the originally requested page in a cookie context.Response.Cookies.Append("requestedurl", currenturi); context.Response.Redirect(redirectUrl); context.HandleResponse(); string hdrJWT = string.Empty; string jwtDetail = string.Empty; try { hdrJWT = _JWTHelper.getBearerHeaderValue(context.Request.Headers); if (!String.IsNullOrEmpty(hdrJWT)) { string format = "yyyy-MM-dd HH:mm:ss:fffffff"; string currentUTC = DateTime.UtcNow.ToString(format); string detailMsg = context.AuthenticateFailure.Message; string jwtEXP = _JWTHelper.getClaim(JwtRegisteredClaimNames.Exp.ToString()).Value; string jwtExpAsDate = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(Convert.ToDouble(jwtEXP)).ToString(format); jwtDetail = $"JWT Expires: {jwtExpAsDate} JWT EXP: {jwtEXP} Current Time: {currentUTC} Auth Error: {detailMsg} "; } } catch (Exception ex) { string setBreakPointHere = ex.Message; } string msg = String.IsNullOrEmpty(context.ErrorDescription) ? String.Empty : $"EXCEPTION: {context.Error} - {context.ErrorDescription}"; string errorMsg = $"ERROR: Missing or invalid JWT. {msg} JWT: {hdrJWT} DETAIL: {jwtDetail}"; Console.WriteLine("USER AUTHENTICATION", "Startup.cs", "ConfigureServices.OnChallenge", errorMsg); return(Task.FromResult(0)); } }; }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <ICryptoHelper, CryptoHelper>(); services.AddScoped <ICookieHelper, CookieHelper>(); services.AddScoped <IJWTHelper, JWTHelper>(); services.AddScoped <IProxyHelper, ProxyHelper>(); // Convert all generated URLs to lowercase. services.AddRouting(options => { options.LowercaseUrls = true; }); // Default all controller actions to require authentication unless adorned with [AllowAnonymous]. services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); }
public IdentityService(IBaseRepo <Account> accountRepo, IJWTHelper jwtHelper) { _accountRepo = accountRepo; _jwtHelper = jwtHelper; }
public DataStoreProvider(IJWTHelper _myJWTHelper) { this.myJWTHelper = _myJWTHelper; }