public AuthenticationService(IUserServiceClient serviceClient, IJwtTokenHandler jwtTokenHandler, JwtTokenSettings jwtTokenSettings) { _serviceClient = serviceClient; _jwtTokenHandler = jwtTokenHandler; _jwtTokenSettings = jwtTokenSettings; }
public static void SetDependency(ref IServiceCollection services, InternalApiCredential internalApiCredential, string authenticationInternalUrl, JwtTokenSettings jwtTokenSettings, JwtTokenValidation jwtTokenValidation) { services.AddSingleton <IBusinessApiAuthentication>(a => new BusinessApiAuthentication(internalApiCredential)); services.AddScoped <IBusinessAuthentications>(a => new BusinessAuthentications(jwtTokenSettings, jwtTokenValidation)); services.AddScoped <IBusinessUsers>(a => new BusinessUsers(a.GetService <IBusinessApiAuthentication>(), authenticationInternalUrl)); }
public OAuthController(DbConnection connection, JwtTokenSettings tokenSettings, IEntityStore entityStore, IDataProtectionProvider dataProtectionProvider) { _connection = connection; _tokenSettings = tokenSettings; _entityStore = entityStore; _dataProtector = dataProtectionProvider.CreateProtector("OAuth tokens"); }
public static IServiceCollection AddCustomAuthenication(this IServiceCollection services) { // Get the token settings var tokenSettings = new JwtTokenSettings(); Startup.Configuration.GetSection("JwtTokenSettings").Bind(tokenSettings); services.AddSingleton(tokenSettings); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); services.AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(opt => { opt.RequireHttpsMetadata = false; opt.Audience = tokenSettings.Audience; opt.Authority = tokenSettings.Authority; opt.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.Key)), ValidateAudience = true, ValidateLifetime = true, ValidAudience = tokenSettings.Audience, RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" }; }); return(services); }
public TokenService( IAuthCertificateModule certificateModule, JwtTokenSettings tokenConfig) { _certificateModule = certificateModule; _tokenConfig = tokenConfig; }
/// <summary> /// Initializes a new instance of the <see cref="JwtTokenService"/> class. /// </summary> /// <param name="settings">The JWT token settings.</param> /// <param name="refreshTokenRepo">The refresh token repo.</param> public JwtTokenService( JwtTokenSettings settings, IRefreshTokenRepository?refreshTokenRepo = null) { Settings = settings ?? new JwtTokenSettings(); RefreshTokenRepo = refreshTokenRepo; }
public static IServiceCollection AddCustomAuthenication(this IServiceCollection services) { var tokenSettings = new JwtTokenSettings(); Startup.Configuration.GetSection("JwtTokenSettings").Bind(tokenSettings); services.AddSingleton(tokenSettings); services.AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(opt => { opt.RequireHttpsMetadata = false; opt.Audience = tokenSettings.Audience; opt.Authority = tokenSettings.Authority; opt.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.Key)), ValidateIssuer = false, ValidateAudience = false }; }); return(services); }
public AuthsController(IOptions <IdentityOptions> identityOptions, SignInManager <ApplicationUser> signInManager, UserManager <ApplicationUser> userManager, JwtTokenSettings tokenSettings) { _identityOptions = identityOptions; _signInManager = signInManager; _userManager = userManager; }
public virtual JwtTokenSettings SetupJwtTokenSettings() { var jwtSettings = new JwtTokenSettings(); configuration.GetSection("Jwt").Bind(jwtSettings); return(jwtSettings); }
public AutenticacaoService(IAutenticacaoRepository autenticacaoRepository, IOptions <JwtTokenSettings> jwtTokenSettings, IOptions <AutorizacaoSettings> autorizacaoSettings) { this.autenticacaoRepository = autenticacaoRepository; this.jwtTokenSettings = jwtTokenSettings?.Value; this.autorizacaoSettings = autorizacaoSettings?.Value; }
public AccountController( UserManager <User> userManager, ApplicationDbContext context, IConfiguration configuration, IOptions <JwtTokenSettings> jwtTokenSettings ) { this._userManager = userManager; this._context = context; _configuration = configuration; this._jwtTokenSettings = jwtTokenSettings.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); //add database based localization services.AddSqlLocalization(options => { var conString = Configuration["ConnectionStrings:ConnectionString"]; options.ConnectionString = conString; }); //Enable JWTToken validation and Authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearerPerTenant((options, tenant) => { var settings = new JwtTokenSettings { SigningKey = tenant.SigningKey, Issuer = tenant.HostName, Audience = tenant.TenantName }; var provider = new JwtTokenProvider(settings); options.TokenValidationParameters = provider.GetTokenValidationParameters(); }); //Enable Scope based authorization services.AddAuthorization(); services.AddSingleton <IAuthorizationPolicyProvider, ScopeAuthorizationPolicyProvider>(); services.AddSingleton <IAuthorizationHandler, ScopeAuthorizationHandler>(); services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new List <CultureInfo> { new CultureInfo("en-US"), new CultureInfo("ne-NP") }; options.DefaultRequestCulture = new RequestCulture(supportedCultures.First()); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); //Register repository and business services Register(services); }
public AdminController(APContext context, IEntityStore entityStore, EntityData entityData, JwtTokenSettings tokenSettings, SignInManager <APUser> signInManager, IServiceProvider provider, IConfigurationRoot configuration, EntityFlattener flattener, UserManager <APUser> userManager, RelevantEntitiesService relevantEntities, CollectionTools collectionTools) { _context = context; _entityStore = entityStore; _entityData = entityData; _tokenSettings = tokenSettings; _signInManager = signInManager; _provider = provider; _configuration = configuration; _flattener = flattener; _userManager = userManager; _relevantEntities = relevantEntities; _collectionTools = collectionTools; }
public AuthController(APContext context, UserManager <APUser> userManager, SignInManager <APUser> signInManager, JwtTokenSettings tokenSettings, EntityFlattener entityFlattener, IEntityStore entityStore, AtomEntryParser entryParser, AtomEntryGenerator entryGenerator, EntityData entityConfiguration, IDataProtectionProvider dataProtectionProvider, IConfigurationRoot configuration, DeliveryService deliveryService) { _context = context; _userManager = userManager; _signInManager = signInManager; _tokenSettings = tokenSettings; _entityFlattener = entityFlattener; _entityStore = entityStore; _entryParser = entryParser; _entryGenerator = entryGenerator; _entityConfiguration = entityConfiguration; _dataProtector = dataProtectionProvider.CreateProtector("OAuth tokens"); _configuration = configuration; _deliveryService = deliveryService; }
async Task <JwtToken> CreateTokenAsync(TokenRequestArgs args) { //sign and return access token along with refresh token var settings = new JwtTokenSettings { SigningKey = _tenant.SigningKey, Issuer = _tenant.HostName, Audience = _tenant.TenantName }; var provider = new JwtTokenProvider(settings); var token = await provider.SignAsync(args.username, null); token.refresh_token = args.refresh_token; return(token); }
public SettingsController(DbConnection connection, IEntityStore entityStore, EntityData entityData, JwtTokenSettings tokenSettings, SignInManager <APUser> signInManager, IServiceProvider provider, IConfigurationRoot configuration, EntityFlattener flattener, UserManager <APUser> userManager, RelevantEntitiesService relevantEntities, CollectionTools collectionTools, TemplateService templateService) { _connection = connection; _entityStore = entityStore; _entityData = entityData; _tokenSettings = tokenSettings; _signInManager = signInManager; _provider = provider; _configuration = configuration; _flattener = flattener; _userManager = userManager; _relevantEntities = relevantEntities; _collectionTools = collectionTools; _templateService = templateService; }
public AuthenticationModule(ICommandDispatcher commandDispatcher, IValidatorResolver validatorResolver, IIdentityProvider identityProvider, IUserStorage userStorage, IOperationStorage operationStorage, IJwtTokenHandler jwtTokenHandler, JwtTokenSettings jwtTokenSettings) : base(commandDispatcher, validatorResolver, identityProvider, modulePath: "") { Post("sign-in", async(ctx, p) => await For <SignIn>() .Set(c => { c.IpAddress = Request.UserHostAddress; c.UserAgent = Request.Headers.UserAgent; }) .SetResourceId(c => c.SessionId) .OnSuccess(async c => { var operation = await operationStorage.GetUpdatedAsync(c.Request.Id); if (operation.HasNoValue || !operation.Value.Success) { return(HttpStatusCode.Unauthorized); } var session = await userStorage.GetSessionAsync(c.SessionId); if (session.HasNoValue) { return(HttpStatusCode.Unauthorized); } return(new { token = jwtTokenHandler.Create(session.Value.UserId), sessionId = session.Value.Id, sessionKey = session.Value.Key, expiry = DateTime.UtcNow.AddDays(jwtTokenSettings.ExpiryDays).ToTimestamp() }); }) .DispatchAsync()); Post("sign-up", async args => await For <SignUp>() .OnSuccessAccepted("account") .DispatchAsync()); Post("sign-out", async args => await For <SignOut>() .OnSuccess(HttpStatusCode.NoContent) .DispatchAsync()); }
public GetEntityHandler(APContext acontext, EntityFlattener flattener, IEntityStore mainStore, AtomEntryGenerator entryGenerator, IServiceProvider serviceProvider, DeliveryService deliveryService, EntityData entityData, ClaimsPrincipal user, CollectionTools collectionTools, INotifier notifier, JwtTokenSettings tokenSettings) { _context = acontext; _flattener = flattener; _mainStore = mainStore; _entryGenerator = entryGenerator; _serviceProvider = serviceProvider; _entityData = entityData; _deliveryService = deliveryService; _user = user; _collectionTools = collectionTools; _notifier = notifier; _tokenSettings = tokenSettings; }
public AuthController(DbConnection connection, UserManager <APUser> userManager, SignInManager <APUser> signInManager, JwtTokenSettings tokenSettings, EntityFlattener entityFlattener, IEntityStore entityStore, EntityData entityConfiguration, IDataProtectionProvider dataProtectionProvider, IConfigurationRoot configuration, DeliveryService deliveryService, SignatureVerifier verifier, IServiceProvider provider, CollectionTools collectionTools, RelevantEntitiesService relevantEntities) { _connection = connection; _userManager = userManager; _signInManager = signInManager; _tokenSettings = tokenSettings; _entityFlattener = entityFlattener; _entityStore = entityStore; _entityConfiguration = entityConfiguration; _dataProtector = dataProtectionProvider.CreateProtector("OAuth tokens"); _configuration = configuration; _deliveryService = deliveryService; _verifier = verifier; _provider = provider; _collectionTools = collectionTools; _relevantEntities = relevantEntities; }
public override void StartModule(IContainer container, ILifetimeScope scope) { _logger = Context.Logger; // Load the settings. NetFusion will throw an exception if the settings // do not pass validation. _tokenSettings = scope.Resolve <JwtTokenSettings>(); // Load the x509 certificate from file. X509Certificate2 cert = LoadCertificate(_tokenSettings); // Store reference to the certificate private-key. _privateKey = new X509SecurityKey(cert) { KeyId = JwtKid.GetHeaderValueForCert(cert) }; }
public GetEntityHandler(DbConnection connection, EntityFlattener flattener, IEntityStore mainStore, IServiceProvider serviceProvider, DeliveryService deliveryService, ServerConfig entityData, ClaimsPrincipal user, CollectionTools collectionTools, INotifier notifier, JwtTokenSettings tokenSettings, SignatureVerifier verifier, IAuthorizer authorizer) { _connection = connection; _flattener = flattener; _mainStore = mainStore; _serviceProvider = serviceProvider; _entityData = entityData; _deliveryService = deliveryService; _user = user; _collectionTools = collectionTools; _notifier = notifier; _tokenSettings = tokenSettings; _verifier = verifier; _authorizer = authorizer; }
public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { var jwtSettings = new JwtTokenSettings(); configuration.GetSection("Jwt").Bind(jwtSettings); services.AddAuthentication() .AddJwtBearer(buider => { buider.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidIssuer = jwtSettings.Issuer, ValidAudience = jwtSettings.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)) }; }); }
// Reads certificate containing Public/Private keys private byte[] ReadCertificateBytes(JwtTokenSettings tokenSettings) { if (!File.Exists(tokenSettings.CertificateFilePath)) { throw new FileNotFoundException("Certificate file could not found.", tokenSettings.CertificateFilePath); } byte[] fileBytes = null; try { fileBytes = File.ReadAllBytes(tokenSettings.CertificateFilePath); } catch (Exception ex) { throw new FileLoadException("Certificate file could not be loaded.", tokenSettings.CertificateFilePath, ex); } return(fileBytes); }
public static IServiceCollection AddCustomOpenIddict(this IServiceCollection services) { var tokenSettings = new JwtTokenSettings(); Startup.Configuration.GetSection("JwtTokenSettings").Bind(tokenSettings); services.AddSingleton(tokenSettings); services.AddOpenIddict <Guid>(options => { options.AddEntityFrameworkCoreStores <ApplicationDbContext>(); options.AddMvcBinders(); // Enable the token endpoint. // Form password flow (used in username/password login requests) options.EnableTokenEndpoint("/connect/token") // Enable the authorization endpoint. // Form implicit flow (used in social login redirects) .EnableAuthorizationEndpoint("/connect/authorize") .EnableTokenEndpoint("/connect/token") .EnableUserinfoEndpoint("/api/userinfo"); // Enable the password and the refresh token flows. options.AllowPasswordFlow() .AllowAuthorizationCodeFlow() .AllowRefreshTokenFlow() // To enable external logins to authenticate .AllowImplicitFlow(); options.RegisterScopes(OpenIdConnectConstants.Scopes.Profile); options.DisableHttpsRequirement(); options.AddSigningKey(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.Key))); options.SetAccessTokenLifetime(TimeSpan.FromMinutes(tokenSettings.TokenLifeTime)); options.SetIdentityTokenLifetime(TimeSpan.FromMinutes(tokenSettings.TokenLifeTime)); options.SetRefreshTokenLifetime(TimeSpan.FromMinutes(tokenSettings.RefreshTokenLifeTime)); options.UseJsonWebTokens(); options.AddEphemeralSigningKey(); }); return(services); }
private X509Certificate2 LoadCertificate(JwtTokenSettings tokenSettings) { _logger.LogInformation("Loaded Certificate File {Named}", tokenSettings.CertificateFilePath); byte[] certBytes = ReadCertificateBytes(tokenSettings); X509Certificate2 cert = null; try { cert = new X509Certificate2(certBytes); } catch (Exception ex) { throw new ContainerException( $"Certificate could not be loaded from file: {tokenSettings.CertificateFilePath}", ex); } _logger.LogDebug(LogEvents.CertFileLoaded, "Certificate file loaded from: {CertFilePath}", tokenSettings.CertificateFilePath); return(cert); }
public virtual string CreateJwtToken(TFor model, params Claim[] extra) { JwtTokenSettings = JwtTokenSettings ?? SetupJwtTokenSettings(); //Set the claims for the token var claims = new List <Claim>() { //Set a unique key for the clam new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.Name, model.Id.ToString()), new Claim(ClaimTypes.Role, typeof(TFor).Name) }; foreach (var item in extra) { if (!claims.Contains(item)) { claims.Add(item); } ; } //Create the credentials that are used for the token var credentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtTokenSettings.SecretKey)), SecurityAlgorithms.HmacSha256 ); //Create the jwt token var token = new JwtSecurityToken( issuer: JwtTokenSettings.Issuer, audience: JwtTokenSettings.Audience, claims: claims, expires: DateTime.Now.AddTicks(JwtTokenSettings.ExpireTicks), signingCredentials: credentials ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public BusinessAuthentications(JwtTokenSettings jwtTokenSettings, JwtTokenValidation jwtTokenValidation) { _jwtTokenValidation = jwtTokenValidation; _jwtTokenSettings = jwtTokenSettings; }
public AuthManager(IUserService userService, IUserAdapter userAdapter, IOptions <JwtTokenSettings> jwtTokenSettings) { _userService = userService; _userAdapter = userAdapter; _jwtTokenSettings = jwtTokenSettings.Value; }
public static void SetDependency(ref IServiceCollection services, string connectionString, JwtTokenSettings jwtTokenSettings, JwtTokenValidation jwtTokenValidation) { services.AddDbContext <Context>(options => options.UseSqlServer(connectionString)); services.AddScoped <DbContext, Context>(); services.AddScoped <IRepoBase, RepoBase>(); services.AddSingleton <IBaseApiConsumer, BaseApiConsumer>(); services.AddScoped <IDataFibonaccis>(a => new DataFibonaccis(connectionString)); services.AddScoped <IBusinessFibonaccis, BusinessFibonaccis>(); var loggerFactory = LoggerFactory.Create(builder => { builder .AddConsole() .AddEventLog(); }); loggerFactory.AddFile("Logs/ErrorLogs-{Date}.txt"); services.AddSingleton(loggerFactory.CreateLogger <Program>()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddScoped <NpgsqlConnection>((svc) => new NpgsqlConnection(Configuration.GetConnectionString("Default"))); services.AddScoped <DbConnection, NpgsqlConnection>((svc) => svc.GetService <NpgsqlConnection>()); services.AddTransient <IUserStore <APUser>, KroegUserStore>(); services.AddTransient <IUserPasswordStore <APUser>, KroegUserStore>(); services.AddTransient <IRoleStore <IdentityRole>, KroegUserStore>(); services.AddIdentity <APUser, IdentityRole>() .AddDefaultTokenProviders(); services.AddAuthorization(options => { options.AddPolicy("admin", policy => policy.RequireClaim("admin")); options.AddPolicy("pass", policy => policy.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme).RequireAuthenticatedUser()); }); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 0; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; }); var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Kroeg")["TokenSigningKey"])); var tokenSettings = new JwtTokenSettings { Audience = Configuration.GetSection("Kroeg")["BaseUri"], Issuer = Configuration.GetSection("Kroeg")["BaseUri"], ExpiryTime = TimeSpan.FromDays(30), Credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), ValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = Configuration.GetSection("Kroeg")["BaseUri"], ValidateAudience = true, ValidAudience = Configuration.GetSection("Kroeg")["BaseUri"], ValidateLifetime = true, ClockSkew = TimeSpan.Zero } }; services.AddSingleton(tokenSettings); services.AddSingleton(new EntityData(Configuration.GetSection("Kroeg")) { EntityNames = Configuration.GetSection("EntityNames") }); services.AddScoped <INotifier, LocalNotifier>(); services.AddSingleton(Configuration); services.AddTransient <IAuthorizer, DefaultAuthorizer>(); services.AddTransient <DeliveryService>(); services.AddTransient <RelevantEntitiesService>(); services.AddTransient <ActivityService>(); services.AddTransient <AtomEntryParser>(); services.AddTransient <AtomEntryGenerator>(); services.AddScoped <TripleEntityStore>(); services.AddScoped <CollectionTools>(); services.AddScoped <FakeEntityService>(); services.AddScoped <EntityFlattener>(); services.AddScoped <KeyService>(); services.AddScoped <IEntityStore>((provider) => { var triple = provider.GetRequiredService <TripleEntityStore>(); var flattener = provider.GetRequiredService <EntityFlattener>(); var httpAccessor = provider.GetService <IHttpContextAccessor>(); var fakeEntityService = provider.GetService <FakeEntityService>(); var retrieving = new RetrievingEntityStore(triple, flattener, provider, httpAccessor); return(new FakeEntityStore(fakeEntityService, retrieving)); }); services.AddSingleton <TemplateService>(); services.AddTransient <SignatureVerifier>(); services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = IdentityConstants.ApplicationScheme; o.DefaultSignInScheme = IdentityConstants.ApplicationScheme; }) .AddJwtBearer((options) => { options.TokenValidationParameters = tokenSettings.ValidationParameters; options.Audience = Configuration.GetSection("Kroeg")["BaseUri"]; options.ClaimsIssuer = Configuration.GetSection("Kroeg")["BaseUri"]; }); services.ConfigureApplicationCookie((options) => { options.Cookie.Name = "Kroeg.Auth"; options.LoginPath = "/auth/login"; }); var typeMap = new Dictionary <string, Type>(); foreach (var module in Configuration.GetSection("Kroeg").GetSection("Modules").GetChildren()) { var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), module.Value)); foreach (var type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(BaseHandler))) { typeMap[type.FullName] = type; } } } foreach (var extra in Configuration.GetSection("Kroeg").GetSection("Filters").GetChildren()) { if (typeMap.ContainsKey(extra.Value)) { EntityData.ExtraFilters.Add(typeMap[extra.Value]); } } services.AddScoped <DatabaseManager>(); }