Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseCors(CorsOptions.AllowAll);

            /*
             * var IDSBearerOption = new IdentityServerBearerTokenAuthenticationOptions
             * {
             *  AuthenticationType = "Bearer",
             *  Authority = "https://localhost:5001",
             *  //ValidationMode = ValidationMode.Local,
             *  ValidationMode = ValidationMode.Local,
             *  RequiredScopes = new[] { "api1" },
             *  ClientId = "testResource",
             *  PreserveAccessToken = true,
             *
             * };
             *
             * app.UseIdentityServerBearerTokenAuthentication(IDSBearerOption);
             */


            var IDSBearerOption = new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions
            {
                TokenValidationParameters = new TokenValidationParameters()
                {
                    //ValidAudience = "https://localhost:5001" ,
                    //ValidIssuer = "testResource" ,
                    //SaveSigninToken =true,
                    RoleClaimType = "role",

                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    //ValidateIssuerSigningKey = false,
                    ValidIssuer   = "testResource",
                    ValidAudience = "https://localhost:5001",

                    //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key_12345"))
                },
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
            };

            app.UseJwtBearerAuthentication(IDSBearerOption);



            //Add a policy "Apiscope"
            app.UseAuthorization(opt =>
            {
                opt.AddPolicy("Apiscope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    //policy.RequireClaim("Scope", "api1", "api2");
                    policy.RequireClaim("Scope", "api1");
                });
            }
                                 );

            //Add a policy "Apiscope2"
            app.UseAuthorization(opt =>
            {
                opt.AddPolicy("Apiscope2", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("Scope", "api2");
                });
            });

            app.UseAuthorization(opt =>
            {
                opt.AddPolicy("adminusers", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("role", "admin");
                });
            });



            //configure web api
            var config = new HttpConfiguration();


            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(IDSBearerOption.AuthenticationType));

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.Formatters.Remove(config.Formatters.XmlFormatter);



            //app.UseCors(CorsOptions.AllowAll);
            //app.UseNLog((eventType) => LogLevel.Debug);



            app.UseWebApi(config);
        }