Esempio n. 1
0
        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;
            });
        }
Esempio n. 2
0
        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();
        }
Esempio n. 3
0
        private static SymmetricSecurityKey CreateSymmetricSecurityKey(TokenAuthenticationOptions options)
        {
            var signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(options.SecretKey));

            return(signingKey);
        }
Esempio n. 4
0
        public static void UseJwtTokenGenerator(this IServiceCollection services, TokenAuthenticationOptions options)
        {
            var signingKey = CreateSymmetricSecurityKey(options);

            services.Configure <TokenProviderOptions>(x =>
            {
                x.Path               = options.TokenPath;
                x.Audience           = options.Audience;
                x.Issuer             = options.Issuer;
                x.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            });
        }
        public async Task Invoke(HttpContext context)
        {
            var scheme = CookieAuthenticationDefaults.AuthenticationScheme;

            if (TokenAuthenticationOptions.IsRequestCanidate(context))
            {
                scheme = TokenAuthenticationOptions.AuthenticationScheme;
            }
            var result = await context.AuthenticateAsync(scheme);

            if (result.Succeeded)
            {
                context.User = result.Principal;
            }
            await _next(context);
        }
Esempio n. 6
0
        public static void SetupJwtTokenGenerator(this IApplicationBuilder app, TokenAuthenticationOptions options)
        {
            var signingKey = CreateSymmetricSecurityKey(options);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer      = options.Issuer,
                ValidateAudience = true,
                ValidAudience    = options.Audience,
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters,
                RequireHttpsMetadata      = true
            });
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                options.SerializerSettings.DateFormatHandling   = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.DateParseHandling    = DateParseHandling.DateTimeOffset;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors();

            // TODO: DataBase 설정 관련 간소화 작업 (DB설정 내부에 쿼리 설정 포함)
            services.AddLeafDataAccess(options =>
            {
                var databases = new List <DatabaseInformationOptions>();
                var queries   = new QueryDirectoryOptions();

                Configuration.GetSection("databases").Bind(databases);
                Configuration.GetSection("queries").Bind(queries);
                options.Databases = databases;
                options.Queries   = queries;
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>     // TODO: 자체 JwtBearer 설정을 하는 확장메서드 생성
            {
                var tokenOptions = new TokenAuthenticationOptions();
                Configuration.GetSection("authentication").Bind(tokenOptions);

                // TODO: TokenValidationParameters 정보를 중앙 관리하도록 리팩토링
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(tokenOptions.Secret))
                };

                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = (context) =>
                    {
                        // Skip the default logic.
                        context.HandleResponse();
                        // WWW-Authenticate →Bearer error="invalid_token", error_description="The token is expired"
                        context.Response.Headers.Add("WWW-Authenticate",
                                                     $"Bearer error=\"{context.Error}\", error_description=\"{context.ErrorDescription}\"");
                        context.Response.Headers.Add("Content-Type", "application/json; charset=utf-8");

                        var payload = new JObject
                        {
                            ["message"]   = context.ErrorDescription,
                            ["error"]     = context.Error,
                            ["error_uri"] = context.ErrorUri
                        };
                        return(context.Response.WriteAsync(payload.ToString()));
                    }
                };
            });

            services.AddSingleton <IConfiguration>(Configuration);
            services.AddSingleton <IEnvironmentProvider, EnvironmentProvider>();
            services.AddSingleton <JwtTokenProvider>();
            services.AddSingleton <AuthenticationService>();
            services.AddSingleton <AccountRepository>();
            services.AddScoped <ObjectResultExceptionFilterAttribute>();

            services.AddLeafModules(new LeafModulesOptions
            {
                BasePath = Path.Combine(HostingEnvironment.ContentRootPath, "Modules"),
                Shutdown = Program.Shutdown
            });
        }
Esempio n. 8
0
        public static IApplicationBuilder UseTokenAuthentication(this IApplicationBuilder app, TokenAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <TokenAuthenticationMiddleware>(Options.Create(options)));
        }