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; }); }
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 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); }
// 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(); }
// 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) { // 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>(); }