Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AudienceDbContext>(builder =>
            {
                builder.UseSqlite("Filename=./audience.db");
            });
            string keyDir = PlatformServices.Default.Application.ApplicationBasePath;

            if (RsaUtils.TryGetKeyParameters(keyDir, false, out RSAParameters keyparams) == false)
            {
                _tokenOptions.Key = default(RsaSecurityKey);
            }
            else
            {
                _tokenOptions.Key = new RsaSecurityKey(keyparams);
            }
            _tokenOptions.Issuer      = "TestIssuer";
            _tokenOptions.Audience    = "TestAudience";
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);
            services.AddSingleton(_tokenOptions);


            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .AddRequirements(new ValidJtiRequirement())
                               .Build());
            });

            services.AddAuthentication().AddJwtBearer(jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = _tokenOptions.Key,
                    ValidAudience    = _tokenOptions.Audience,
                    ValidIssuer      = _tokenOptions.Issuer,
                    ValidateLifetime = true
                };
            });

            services.AddScoped <IAuthorizationHandler, ValidJtiHandler>();
            // Add framework services.
            services.AddMvc();
        }