Exemple #1
0
        public static string GenerateToken(Customer customer)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(JWT.GetInstance().Secret);

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.Role, "User"),
                    new Claim(ClaimTypes.SerialNumber, customer.Cpf),
                }),
                Expires            = DateTime.UtcNow.AddDays(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = handler.CreateToken(descriptor);

            return(handler.WriteToken(token));
        }
Exemple #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();

            // Inject JWT Settings
            string secret = Configuration.GetSection("JWT").GetSection("Secret").Value;

            JWT.GetInstance().Secret = secret;

            // JWT Settings
            var key = Encoding.ASCII.GetBytes(secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                };
            });

            // Database Connection
            string connection = Configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;

            services.AddDbContext <ProductContext>(option =>
                                                   option.UseLazyLoadingProxies().UseMySql(connection, migration =>
                                                                                           migration.MigrationsAssembly("Repository")));

            // Scope's
            services.AddScoped <IOrderRepository, OrderRepository>();
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <ICustomerRepository, CustomerRepository>();
        }