public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(auth => { auth.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser().Build(); auth.AddPolicy("Admin", new AuthorizationPolicyBuilder() .RequireAuthenticatedUser().RequireClaim("IsAdmin", new[] { "True" }).Build()); }); _RSAKey = new RsaSecurityKey(RSAKeyUtils.GetRandomKey()); _tokenOptions = new TokenAuthenticationOptions ( Audience: "EvidencijaUsers", Issuer: "EvidencijaWebService", SigningCredentials: new SigningCredentials(_RSAKey, SecurityAlgorithms.RsaSha256Signature) ); services.AddSignalR(options => { options.Hubs.EnableDetailedErrors = true; }); services.AddDbContext <EvidencijaDbContext>(options => { options.UseSqlServer(Config["ConnectionString"]); }); services.AddScoped <IDbContextBinder, DbContextBinder>(); services.AddSingleton <UserCollection>(); services.AddSingleton <TokenAuthenticationOptions>(_tokenOptions); services.AddSingleton <JwtTokenProvider>(); services.AddMvc(); }
public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(auth => { auth.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser().Build(); }); _RSAKey = new RsaSecurityKey(RSAKeyUtils.GetRandomKey()); _tokenOptions = new TokenAuthenticationOptions ( Audience: "QuizUsers", Issuer: "QuizApp", SigningCredentials: new SigningCredentials(_RSAKey, SecurityAlgorithms.RsaSha256Signature) ); services.AddDbContext <QuizDbContext>(options => options.UseSqlServer((Config["IsDev"] == "True") ? Config["ConnectionStrings:LocalConnection"] : Config["ConnectionStrings:ServerConnection"])); services.AddSingleton <TokenAuthenticationOptions>(_tokenOptions); services.AddSingleton <JwtTokenProvider>(); services.AddSingleton <IConfiguration>(Config); services.AddScoped <QuizDbRepo>(); services.AddScoped <QuestionRepository>(); services.AddScoped <AnswerRepository>(); services.AddScoped <TeamRepository>(); services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); }
// This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddCaching(); services.AddSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); services.AddMvc(options => { options.Filters.Add(new GlobalExceptionFilter()); }); services.Configure <AppSettings>(Configuration.GetSection("AppSettings")); var appSettings = Configuration.Get <AppSettings>(); key = RSAKeyUtils.GetKey(); tokenOptions = new TokenAuthOptions("ExampleAudience", "ExampleIssuer", key); services.AddInstance <TokenAuthOptions>(tokenOptions); services.AddAuthorization(auth => { auth.AddPolicy(TokenAuthOptions.Scheme, new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(TokenAuthOptions.Scheme) .RequireAuthenticatedUser() .AddRequirements(new TokenAuthRequirement()) .Build()); }); DependencyInstaller.InjectDependencies(services, this.Configuration); _logger.LogInformation("Configuring Services"); }
public static void AddAppWebSecurity(this IServiceCollection services, IHostingEnvironment env) { //RSAKeyUtils.GenerateKeyAndSave(env.ContentRootPath + "\\App_Data\\RSAkey.txt"); RSAParameters keyParams = RSAKeyUtils.GetKeyParameters(env.ContentRootPath + "\\App_Data\\RSAkey.txt"); var key = new RsaSecurityKey(keyParams); services.Configure <TokenAuthOptions>(tokenAuthOptions => { tokenAuthOptions.Audience = GetAudience(); tokenAuthOptions.Issuer = GetIssuer(); tokenAuthOptions.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature); tokenAuthOptions.IssuerSigningKey = key; }); services.AddAuthorization(auth => { auth.AddPolicy(ApiConstants.ApiPolicy, new AuthorizationPolicyBuilder() //.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme) .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build()); }) .AddAuthentication(o => { o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.Cookie.Name = ".BaseApp.Web-Core-AUTH"; options.LoginPath = new PathString("/Account/LogOn/"); options.LogoutPath = new PathString("/Account/LogOff/"); options.AccessDeniedPath = new PathString("/Account/Forbidden/"); }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateIssuer = true, ValidIssuer = GetIssuer(), ValidateAudience = true, ValidAudience = GetAudience(), ValidateLifetime = true, // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time // when validating the lifetime. As we're creating the tokens locally and validating them on the same // machines which should have synchronised time, this can be set to zero. Where external tokens are // used, some leeway here could be useful. ClockSkew = TimeSpan.FromMinutes(0) }; options.RequireHttpsMetadata = false; }); }
private void ConfigAuth(IServiceCollection services) { // *** CHANGE THIS FOR PRODUCTION USE *** // Here, we're generating a random key to sign tokens - obviously this means // that each time the app is started the key will change, and multiple servers // all have different keys. This should be changed to load a key from a file // securely delivered to your application, controlled by configuration. // // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from // a JSON file. var keyParams = RSAKeyUtils.GetKeyParameters(".config/rsaparams.json"); // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. _signingKey = new RsaSecurityKey(keyParams); _tokenOptions = new TokenProviderOptions { Audience = AppSettings.Auth.TokenAudience, Issuer = AppSettings.Auth.TokenIssuer, SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature), IdentityResolver = GetIdentity }; // Save the token options into an instance so they're accessible to the services.AddSingleton(typeof(TokenProviderOptions), _tokenOptions); // Enable Dual Authentication services.AddAuthentication() .AddCookie(cfg => cfg.SlidingExpiration = true) .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = AppSettings.Auth.TokenIssuer, ValidAudience = AppSettings.Auth.TokenAudience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])) }; }); //services.AddAuthentication(options => //{ // options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; //}); // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect. services.AddAuthorization(options => { options.AddPolicy(AuthSchema, policy => { policy.AuthenticationSchemes.Add(AuthSchema); policy.RequireAuthenticatedUser().Build(); }); }); }
public static void RegisterComponents() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers RSAParameters keyParams = RSAKeyUtils.GetRandomKey(); // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. var key = new RsaSecurityKey(keyParams); TokenAuthOptions tokenOptions = new TokenAuthOptions() { Audience = ConfigurationManager.AppSettings["SiteUrl"], Issuer = ConfigurationManager.AppSettings["SiteUrl"], SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) }; container.RegisterInstance <TokenAuthOptions>(tokenOptions); IMemoryCache memorycache = new MemoryCache(new MemoryCacheOptions()); container.RegisterInstance <IMemoryCache>(memorycache); Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions op = new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions(); op.AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active; op.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = key, ValidAudience = tokenOptions.Audience, ValidateIssuerSigningKey = true, ValidateLifetime = true, // For development purpose ClockSkew is set to zero to respect the token validity lifetime set in config. // Token expiration time = Issue time + expiration time in config + ClockSkew ClockSkew = TimeSpan.Zero, ValidateIssuer = true, ValidIssuer = tokenOptions.Issuer }; container.RegisterInstance <Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions>(op); // e.g. container.RegisterType<ITestService, TestService>(); container.RegisterType <ISurveyQuestions, SurveyQuestionsAggregateRoot>(); container.RegisterType <ISurveyRoot, SurveyRoot>(); container.RegisterType <ICreationRepository, CreationRepository>(); container.RegisterType <ISurveyRepository, SurveyRepository>(); container.RegisterType <ISurveyContextAggregator, SurveyContextAggregator>(); container.RegisterType <ISurveyResponse, SurveyResponse>(); container.RegisterType <ISurveyResponseRepository, SurveyResponseRepository>(); container.RegisterType <IAuthenticate, Authenticate>(); container.RegisterType <IAuthorisationRepository, AuthorisationRepository>(); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); }
static void Main(string[] args) { //EXPORTED KEYS string importedPublicKeyBase64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhbVC4aUR+XRCepBcPlod69wruXqwW9yL/YJYvuaQ33QxUoAehQ0z4SuphHwEPxQp/qLqucmE6XKlEeTksFAmaGM88uuGessqMZmdu9WFhc07MWLTCifR43IRtGEeWeFSWjUI6mNRrShP3QQ3+Z6e7w+HRA2RpmgNgEhJRvECHAKpcpHvP9o5Sq6q/dIAyR6NEjRFhfud27rFtnWrLj+ZmIsScemvks4vh8V3n8EzxxRE8nzVuZYr4v4NNH+q95XgIadHZ1Y6ICXJgX2NfacNRQl9+SEv0Wo8lbmFSIO3jHqyiWuSugv7R3/rQPRXHT6HJAtw0tBiPOBitMkTzqOvIwIDAQAB"; string importedPrivateKeyBase64 = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCFtULhpRH5dEJ6kFw+Wh3r3Cu5erBb3Iv9gli+5pDfdDFSgB6FDTPhK6mEfAQ/FCn+ouq5yYTpcqUR5OSwUCZoYzzy64Z6yyoxmZ271YWFzTsxYtMKJ9HjchG0YR5Z4VJaNQjqY1GtKE/dBDf5np7vD4dEDZGmaA2ASElG8QIcAqlyke8/2jlKrqr90gDJHo0SNEWF+53busW2dasuP5mYixJx6a+Szi+HxXefwTPHFETyfNW5livi/g00f6r3leAhp0dnVjogJcmBfY19pw1FCX35IS/RajyVuYVIg7eMerKJa5K6C/tHf+tA9FcdPockC3DS0GI84GK0yRPOo68jAgMBAAECggEAJ/Dalr8RnHvPM/+Vnoaa847kfNaaggZixwq96eDEHAwAg82D0Gj+O2AolkvZlOI4HTmbdn4tNvMpPiwq6EQ5BOvIFCSpGltAMmraBHcnGK4S5ZDIy/rTJuc3RLPSNjUpvYqkLCgZCOnG2ZXeBrIMdgskc/69qIDir5RoV0m9QJJYU7pfrfErWYr/eqb1t7eZtTBAg+LAjKUMUq68WoJiBSBRPbAvlyFoc6tyk0ftngsF4OPVbwZQyYC2vLmxVrr1/YQbEgjpuJwQ0bONL6G9PAH6O+h10ILk9nyJY2c9gOXU0tz+foJ47naM12wCJETEy9JGeAiN4NLz5wRKTZzZwQKBgQDCOEJGDgtmSM0bDv4vPuxbacFgGTgRAKTs6sG9E1Cf3LNBLDP9OhfRkXFc192PmQRAktaZAN89zXeGxK1tLbJ3003qKXw05K3KOksVjJ7AH4Yhurv3VWmFZB8pryUsxIp+rm/5GLf4LfptUmBO6R4+jTfJVRBtK4A9KmkbY7BjgwKBgQCwPWayTgd0fmDqJxptWfPThcUw3/cG6EWTpnx1dSOdaBHzewRwq/8/i4vs314/onLggXgZTIkPU7y8ylTmz5KcaPIQkmRSSSL0Y2yzMGcHnylj7ysgBLw23k/PVzGSsMZ6ly7lE03SNQ3tyg6u0lc3pbT8ZLHf/x913stxSSiT4QKBgQChdgnKmZRqhS1WSGGSP3pZCJNFY9HTeLijaQqFOFB3hg/Tp37VDv2MMKCQsbi0z13UnP4glrQAehbbCBixQiMzMIx+ldx3UIEWNN4E3TGAwPROiCIJnY0q4rBxg/SgwgftBvF5oU4X2YluZuQ/1ddZ4ya0jq4oQ9jJgL9+kKKsJwKBgQCndbBfPEVZK7xqwT0bKp3EHxd/mU/gAFQcN9WKxgNRTdHAyOMvLD8c4jvSl2u2i2UcbejwIQkaxzZPLPH/XrywYgegN3mbtmLAVLi0iwla9KEfk+ImSlmMyTCMkw1HlTECyySEBhOr6T2S9Kt+8d5twcZ3DDb34DLEjS5CNoGYAQKBgDCEyhrg2lwyYwrL26ohNNuzgiabC5IKCgHlMpsUQjoCid9awCSb2iROf7iZIBoDyzXqgEQWTAf2clpJxgHz0necVw2sXP8wGcJXJ+e/lXNfPaC4z2QRnQ6i2iV88jRlWLK+S403hGnK0L/SDu9LtBhHwy6r/qRGT14ourqS6x7O"; byte[] importedPublicKeyBytes = Convert.FromBase64String(importedPublicKeyBase64); byte[] importedPrivateKeyBytes = Convert.FromBase64String(importedPrivateKeyBase64); //PRINT INFO Console.WriteLine("------ IMPORTED KEY PAIR: ------\n"); Console.WriteLine("PUBLIC KEY:\n" + importedPublicKeyBase64 + "\n\n"); Console.WriteLine("PRIVATE KEY:\n" + importedPrivateKeyBase64 + "\n\n"); //GENERATING RSACRYPTOSERVICEPROVIDER FROM X509 PUBLIC KEY BLOB using (var providerFromX509pubKey = RSAKeyUtils.DecodePublicKey(importedPublicKeyBytes)) { providerFromX509pubKey.PersistKeyInCsp = false; //DO NOT STORE IN KEYSTORE //EXPORT TO X509 PUBLIC KEY BLOB byte[] x509pubKeyBytes = RSAKeyUtils.PublicKeyToX509(providerFromX509pubKey.ExportParameters(false)); //CONVERT TO BASE64 string x509pubKeyBase64 = Convert.ToBase64String(x509pubKeyBytes); //PRINT INFO Console.WriteLine("------ PUBLIC KEY TO EXPORT ------"); Console.WriteLine("Public key to export matches imported? " + importedPublicKeyBase64.Equals(x509pubKeyBase64)); Console.WriteLine(x509pubKeyBase64 + "\n\n"); } //GENERATING RSACRYPTOSERVICEPROVIDER FROM PKCS8 PRIVATE KEY BLOB using (var providerFromPKCS8privKey = RSAKeyUtils.DecodePrivateKeyInfo(importedPrivateKeyBytes)) { providerFromPKCS8privKey.PersistKeyInCsp = false; //DO NOT STORE IN KEYSTORE //EXPORT TO PKCS8 PRIVATE KEY BLOB byte[] pkcs8privKeyBytes = RSAKeyUtils.PrivateKeyToPKCS8(providerFromPKCS1privKey.ExportParameters(true)); //CONVERT TO BASE64 string pkcs8privKeyBase64 = Convert.ToBase64String(pkcs8privKeyBytes); //PRINT INFO Console.WriteLine("------ PRIVATE KEY TO EXPORT ------"); Console.WriteLine("Private key to export matches imported? " + importedPrivateKeyBase64.Equals(pkcs8privKeyBase64)); Console.WriteLine(pkcs8privKeyBase64); } //PREVENTS THE PROGRAM FROM EXITING Console.ReadKey(); }
private void ConfigureCommonObjects(IServiceCollection services) { AnraConfiguration.Configure(services, Configuration); //services.AddSingleton(new SendNotification(services.BuildServiceProvider().GetRequiredService<AnraConfiguration>())); services.AddSingleton(new TokenProviderOptions { Audience = "AnraUsers", Issuer = "AnraTechnologies", SigningCredentials = new SigningCredentials(new RsaSecurityKey(RSAKeyUtils.GetKey()), SecurityAlgorithms.RsaSha256Signature), Expiration = TimeSpan.FromMinutes(Configuration.GetSection("LoginSettings").GetValue <double>("Expiration")) }); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // Configure auth // Replace this with some sort of loading from config / file. RSAParameters keyParams = RSAKeyUtils.GetRandomKey(); // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. key = new RsaSecurityKey(keyParams); tokenOptions = new TokenAuthOptions() { Audience = TokenAudience, Issuer = TokenIssuer, SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) }; // Save the token options into an instance so they're accessible to the // controller. services.AddSingleton <TokenAuthOptions>(tokenOptions); // Enable the use of an [Authorize("Bearer")] attribute on methods and // classes to protect. services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); // Add framework services. services.AddEntityFrameworkSqlServer() .AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <Tunee, TuneeRole>(options => { options.Cookies.ApplicationCookie.AutomaticChallenge = false; options.Password.RequireDigit = false; options.Password.RequiredLength = 5; // TODO: Store in config somewhere. options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddEntityFrameworkStores <ApplicationDbContext, Guid>() .AddDefaultTokenProviders(); services.AddMvc(); }
public Startup(IHostingEnvironment env) { _keyArtifacts = new KeyArtifacts(); _hostingEnv = env; // If env.ContentRootPath is not set properly (to a dir containing appsettings.json) this next block of code will not find our configuration and we want to raise an exception. // Set up configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddEnvironmentVariables() .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", reloadOnChange: true, optional: true); // Note: hosting.json config builder is a different config builder! if (env.IsEnvironment("Development")) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } builder.AddEnvironmentVariables(); // After this point, configuration gets set. Configuration = builder.Build(); string keyfilename = RSAKeyUtils.InitializeKeyArtifacts(env.WebRootPath, _keyArtifacts); // Log.Warning($"Auth-Environment: {env.EnvironmentName} "); // Log.Warning($"Auth-artifact: {_keyArtifacts}"); // Log.Warning($"Auth-secret:{keyfilename}"); }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { #region Token Config // *** CHANGE THIS FOR PRODUCTION USE *** // Here, we're generating a random key to sign tokens - obviously this means // that each time the app is started the key will change, and multiple servers // all have different keys. This should be changed to load a key from a file // securely delivered to your application, controlled by configuration. // // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from // a JSON file. var keyParams = RSAKeyUtils.GetRandomKey(); //TODO secure storage // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. key = new RsaSecurityKey(keyParams); tokenOptions = new TokenAuthOptions { Audience = Configuration["TokenAudience"], Issuer = Configuration["TokenIssuser"], SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) }; // Save the token options into an instance so they're accessible to the // controller. services.AddSingleton(tokenOptions); // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect. services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() // .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); // services.Configure<Settings>(Configuration.GetSection("App")); #endregion services.AddSignalR(options => { options.Hubs.EnableDetailedErrors = true; }); #region Services services.AddScoped <IOAuthHandler, OAuthHandler>(); services.AddScoped <IMembershipService, MembershipService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IEncryptionService, EncryptionService>(); services.AddScoped <IApiErrorHandler, ApiErrorHandler>(); services.AddScoped <IEventRepository, EventRepository>(); services.AddScoped <ITeamRepository, TeamRepository>(); services.AddTransient <IConnectionManager, ConnectionManager>(); services.AddScoped <IQuestionRepository, QuestionRepository>(); #endregion services.AddIdentity <User, IdentityRole>() .AddEntityFrameworkStores <RscContext>(); services.AddDbContext <RscContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddSwaggerGen(); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddSignalR(); services.AddMvc() .AddJsonOptions(opt => { opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; }); services.AddMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.BufferBodyLengthLimit = Int64.MaxValue; x.MultipartBodyLengthLimit = Int64.MaxValue; }); var sqlConnectionString = Configuration.GetConnectionString("PostgreSqlProviderPath"); services.AddDbContext <MantiDbContext>(options => options.UseNpgsql( sqlConnectionString, b => b.MigrationsAssembly(nameof(MantiScanServices)) ) ); ConfigureCommonObjects(services); services.AddCors(); services.AddIdentity <User, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 6; config.Password.RequireUppercase = false; config.Password.RequireNonAlphanumeric = false; }) .AddEntityFrameworkStores <MantiDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Audience = "AnraUsers"; options.ClaimsIssuer = "AnraTechnologies"; options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = "AnraTechnologies", IssuerSigningKey = new RsaSecurityKey(RSAKeyUtils.GetKey()) }; }); services.AddLogging(loggingBuilder => { loggingBuilder.AddSerilog(); }); services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.AddAuthorization(options => { options.AddPolicy("Bearer", authBuilder => { authBuilder.RequireRole("Administrators"); }); }); AddCustomDependencies(services); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MantiScan API", Version = "MantiScan Services v1.0.0" }); c.DescribeAllEnumsAsStrings(); var basePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, Assembly.GetExecutingAssembly().GetName().Name + ".xml"); c.IncludeXmlComments(basePath); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. #if DEBUG services.AddEntityFramework() .AddSqlServer() .AddDbContext <AuthorizationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:AuthConnectionString"])) .AddDbContext <DataDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:DataConnectionString"])); #elif RELEASE services.AddEntityFramework() .AddSqlServer() .AddDbContext <AuthorizationDbContext>(options => options.UseSqlServer(Configuration["Data:AzureConnection:AuthConnectionString"])) .AddDbContext <DataDbContext>(options => options.UseSqlServer(Configuration["Data:AzureConnection:DataConnectionString"])); services.Configure <MvcOptions>(options => { options.Filters.Add(new RequireHttpsAttribute()); }); #endif services.AddIdentity <ApplicationUser, IdentityRole>(o => { // configure identity options o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonLetterOrDigit = false;; o.Password.RequiredLength = 6; }) .AddEntityFrameworkStores <AuthorizationDbContext>() .AddDefaultTokenProviders(); services.AddScoped <MySignInManager <ApplicationUser>, MySignInManager <ApplicationUser> >(); //rzekomo dzięki temu można zastąpić SignInManagera swoim własnym //Token-based authentication https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample // *** CHANGE THIS FOR PRODUCTION USE *** // Here, we're generating a random key to sign tokens - obviously this means // that each time the app is started the key will change, and multiple servers // all have different keys. This should be changed to load a key from a file // securely delivered to your application, controlled by configuration. // // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from // a JSON file. RSAParameters keyParams = RSAKeyUtils.GetRandomKey(); // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. key = new RsaSecurityKey(keyParams); tokenOptions = new TokenAuthManager() { Audience = TokenAudience, Issuer = TokenIssuer, SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) }; // Save the token options into an instance so they're accessible to the // controller. services.AddInstance <TokenAuthManager>(tokenOptions); // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect. services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().RequireClaim(ClaimTypes.NameIdentifier).Build()); }); //Koniec Token-based authentication services.AddMvc(); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); }