Exemplo n.º 1
0
 /// <summary>
 /// Creates a new instance of <see cref="AuthController"/>.
 /// </summary>
 public AuthController(
     IUserRepository userRepository,
     IJwtUtils utilities,
     IOptions <JwtConfigModel> jwtConfig)
 {
     _userRepository = userRepository;
     _utilities      = utilities;
     _jwtConfig      = jwtConfig.Value;
 }
Exemplo n.º 2
0
 public AccountController(SignInManager <AppIdentityUser> signInManager,
                          UserManager <AppIdentityUser> userManager,
                          IOptions <JwtConfigModel> options,
                          UserPhoneNumberRepository userPhoneNumberRepository,
                          SettingRepository settingRepository)
 {
     this.signInManager         = signInManager;
     this.userManager           = userManager;
     jwtTokenModel              = options.Value;
     _userPhoneNumberRepository = userPhoneNumberRepository;
     _settingRepository         = settingRepository;
 }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var jwtTokenModel = new JwtConfigModel();

            Configuration.GetSection("JwtToken").Bind(jwtTokenModel);

            services.AddDbContext <AppIdentityDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <AppIdentityUser, AppIdentityRole>()
            .AddEntityFrameworkStores <AppIdentityDbContext>()
            .AddDefaultTokenProviders();

            // ===== Add Jwt Authentication ========
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtTokenModel.Issuer,
                    ValidAudience    = jwtTokenModel.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtTokenModel.Key)),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });


            services.Configure <JwtConfigModel>(config => Configuration.GetSection("JwtToken").Bind(config));

            // Comment the next line if your app is running on the .NET Core 2.0
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            RepositoryInjection.Inject(services);

            services.AddMemoryCache(); // Adds a default in-memory
                                       // implementation of
                                       // IDistributedCache

            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
            });

            services.AddAntiforgery(options =>
            {
                options.HeaderName  = "X-XSRF-TOKEN";
                options.Cookie.Name = "MyAntiForgeryCookieName";
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Exemplo n.º 4
0
 public JwtManager(JwtConfigModel jwtConfig)
 {
     _jwtConfig = jwtConfig;
 }
Exemplo n.º 5
0
 /// <summary>
 /// Creates a new instance of <see cref="Utilities"/>.
 /// </summary>
 public Utilities(IOptions <JwtConfigModel> jwtConfig)
 {
     _jwtConfig = jwtConfig.Value;
 }
Exemplo n.º 6
0
 public CryptoService(JwtConfigModel jwtConfig)
 {
     _jwtConfig = jwtConfig;
 }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JwtConfigModel.Init(Configuration);

            services.AddDbContext <MyDBContext>(options =>
            {
                options.UseInMemoryDatabase("TestDB");
            });

            services.AddTransient <IClaimsTransformation, ClaimsTransformer>();
            services.AddTransient <MyDBContext>();


            services.AddScoped <ITokenValidatorService, TokenValidatorService>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew                = TimeSpan.Zero,
                    ValidateIssuer           = true,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer              = Configuration["Jwt:Issuer"],
                    ValidAudience            = Configuration["Jwt:Issuer"],
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>()
                                     .CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        var tokenValidatorService = context.HttpContext.RequestServices
                                                    .GetRequiredService <ITokenValidatorService>();
                        return(tokenValidatorService.ValidateAsync(context));
                    },
                    OnChallenge = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>()
                                     .CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder
                    //.WithOrigins("http://localhost:3000")
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    //.AllowCredentials()
                    .Build();
                });
            });

            services.AddMemoryCache();

            services.AddControllers();
        }