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)
        {
            // Add framework services.
            services.AddDbContext <AuthDbContext>(builder =>
            {
                builder.UseSqlite("Filename=./jwt.db");
            });
            string keyDir = PlatformServices.Default.Application.ApplicationBasePath;

            if (RsaUtils.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
            {
                keyParams = RsaUtils.GenerateAndSaveKey(keyDir);
            }
            _tokenOptions.Key         = new RsaSecurityKey(keyParams);
            _tokenOptions.Issuer      = "TestIssuer";
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);
            services.AddSingleton(_tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            });

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