Пример #1
0
        private async Task <TokenValidationParameters> GetValidationParameters(string issuer)
        {
            var settings = AuthSettingsFactory.GetProviderForIssuer(issuer);

            return(TokenValidationParametersBuilder.Create()
                   .DefaultClockSkew()
                   .ValidateExpiration()
                   .ValidateSigninKey(await GetSigningKeys(issuer)) // TODO: Give the possibility to configure how to get signingKey
                   .ValidateAudiences(settings.Audiences)
                   .ValidateIssuers(settings.Issuer)
                   .Build());
        }
Пример #2
0
        /// <summary>
        /// The configure services.
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">
        /// The services.
        /// </param>
        /// <returns>
        /// The <see cref="IServiceProvider"/>.
        /// </returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
                config =>
            {
                config.TokenValidationParameters =
                    TokenValidationParametersBuilder.GetTokenValidationParameters(Configuration);
            });

            services.AddDbContext <EFContext>(options => { options.UseInMemoryDatabase("MyDatabase"); });
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.Configure <WebEncoderOptions>(
                options => options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All));

            Console.WriteLine($"{Configuration["Email:Server"]}:{Configuration["Email:Port"]}");

            services.AddMailKit(
                optionBuilder =>
            {
                optionBuilder.UseMailKit(
                    new MailKitOptions()
                {
                    // get options from sercets.json
                    Server      = Configuration["Email:Server"],
                    Port        = Convert.ToInt32(Configuration["Email:Port"]),
                    SenderName  = Configuration["Email:SenderName"],
                    SenderEmail = Configuration["Email:SenderEmail"],

                    // can be optional with no authentication
                    Account  = Configuration["Email:Account"],
                    Password = Configuration["Email:Password"],

                    // enable ssl or tls
                    Security = true
                });
            });
            return(services.BuildServiceProvider());
        }
        public static IServiceCollection RegisterWebApiServices(this IServiceCollection services, IConfiguration configuration)
        {
            #region JWT
            services.AddAuthorization(options =>
            {
                options.AddPolicy("DigitalBank-Pub", policy => policy.RequireClaim("Authorization", "Pub-DigitalBank"));
            });

            string secret = configuration["JWT_SECRET"];
            SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));
            var tokenOptions = configuration.GetSection(nameof(AuthorizeOptions));
            var tokenValidationParameters = new TokenValidationParametersBuilder(tokenOptions, signingKey)
                                            .Build();

            services.Configure <AuthorizeOptions>(options =>
            {
                options.Issuer             = tokenOptions[nameof(AuthorizeOptions.Issuer)];
                options.Audience           = tokenOptions[nameof(AuthorizeOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            });

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
            });
            #endregion

            #region Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(configuration["Application:Version"],
                                   new Info
                {
                    Title       = configuration["Application:Title"],
                    Version     = configuration["Application:Version"],
                    Description = configuration["Application:Description"]
                });

                options.AddSecurityDefinition("Bearer",
                                              new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Autenticação baseada em Json Web Token (JWT)",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } }
                });

                var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
                var applicationName     = PlatformServices.Default.Application.ApplicationName;
                var xmlDocumentPath     = Path.Combine(applicationBasePath, $"{applicationName}.xml");

                if (File.Exists(xmlDocumentPath))
                {
                    options.IncludeXmlComments(xmlDocumentPath);
                }
                options.DescribeAllEnumsAsStrings();
            });
            #endregion

            #region AutoMapper
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);
            #endregion

            #region Application

            #region Repository
            services.AddScoped <IDigitalAccountRepository, DigitalAccountRepository>();
            services.AddScoped <ICustomerPermissionRepository, CustomerPermissionRepository>();
            services.AddScoped <ICustomerRepository, CustomerRepository>();
            services.AddScoped <IPermissionRepository, PermissionRepository>();
            #endregion

            #region Handler
            services.AddSingleton <IEncryptorHandler, EncryptorHandler>();
            services.AddSingleton <ITokenHandler, Security.JWT.Handler.TokenHandler>();
            #endregion

            #region Business
            services.AddScoped <IDigitalAccountBusiness, DigitalAccountBusiness>();
            services.AddScoped <ICustomerBusiness, CustomerBusiness>();
            services.AddScoped <ICustomerPermissionBusiness, CustomerPermissionBusiness>();
            services.AddScoped <IPermissionBusiness, PermissionBusiness>();
            #endregion

            #endregion

            return(services);
        }
Пример #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }).AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            #region Authentication

            services.AddAuthorization(options =>
            {
                options.AddPolicy("WebApiUser", policy => policy.RequireClaim("PanelAdministrator", "BackEnd"));
            });

            // Carrega as opções do Token
            var tokenOptions = Configuration.GetSection(nameof(AuthorizeOptions));
            var tokenValidationParameters = new TokenValidationParametersBuilder(tokenOptions, _signingKey)
                                            .Build();

            // Configura as opções do Token
            services.Configure <AuthorizeOptions>(options =>
            {
                options.Issuer             = tokenOptions[nameof(AuthorizeOptions.Issuer)];
                options.Audience           = tokenOptions[nameof(AuthorizeOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
            });

            #endregion

            #region Swagger

            services.AddSwaggerGen(c =>
            {
                c.OperationFilter <AuthorizationHeaderParameterOperationFilter>();
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "API de Autenticação",
                    Description    = "API para criar e validar a autenticação",
                    TermsOfService = "None"
                });

                //var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "mysql.b2b.api.pub.authenticate.xml");
                //c.IncludeXmlComments(filePath);
                c.DescribeAllEnumsAsStrings();
            });
            #endregion

            services.AddTransient <IDataBaseProvider, DataBaseProvider>();
            services.AddTransient <IAuthenticateManager, AuthenticateManager>();
        }