Exemplo n.º 1
0
 // private readonly ExchangeService service = Service.ConnectToService(new FakeUser());
 public AccountController(AppDbContext dbContext,
                          UserManager <ApplicationUser> userManager,
                          SignInManager <ApplicationUser> signInManager,
                          IOptions <TokenAuthOption> tokenOptions)
 {
     this._dbContext     = dbContext;
     this._userManager   = userManager;
     this._signInManager = signInManager;
     this._tokenOptions  = tokenOptions.Value;
 }
Exemplo n.º 2
0
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     ILoggerFactory loggerFactory,
     IOptions <TokenAuthOption> tokenOptions)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _logger        = loggerFactory.CreateLogger <AccountController>();
     _tokenOptions  = tokenOptions.Value;
 }
Exemplo n.º 3
0
        public LoginController(IOptions <TokenAuthOption> jwtParametersOptions, IUsersService usersService, IHostingEnvironment env)
        {
            _jwtParametersOptions = jwtParametersOptions.Value;
            UsersService          = usersService;
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();
        }
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     RoleManager <IdentityRole> roleManager,
     ILoggerFactory loggerFactory,
     IOptions <TokenAuthOption> tokenOptions,
     IOptions <AppSettings> appSettingsAccessor)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _roleManager   = roleManager;
     _logger        = loggerFactory.CreateLogger <AccountController>();
     _tokenOptions  = tokenOptions.Value;
     _appSettings   = appSettingsAccessor.Value;
     _emailSender   = new EmailSender(appSettingsAccessor);
 }
Exemplo n.º 5
0
 public AccountController(
     ReformaAgrariaDbContext context,
     UserManager <ReformaAgrariaUser> userManager,
     SignInManager <ReformaAgrariaUser> signInManager,
     ILogger <AccountController> logger,
     ILogger <MailController> mailLogger,
     IOptions <TokenAuthOption> tokenOptions,
     IConfiguration iconfiguration,
     IAuthorizationService authorizationService
     )
 {
     _context              = context;
     _userManager          = userManager;
     _signInManager        = signInManager;
     _logger               = logger;
     _tokenOptions         = tokenOptions.Value;
     _iconfiguration       = iconfiguration;
     _authorizationService = authorizationService;
     _mailLogger           = mailLogger;
 }
Exemplo n.º 6
0
        public async Task<IActionResult> Token([FromBody] GetTokenDto body) {
            try {
                // Check the password but don't "sign in" (which would set a cookie)
                var user = await _signInManager.UserManager.FindByEmailAsync(body.email);
                if (user == null) {
                    return Json(new {
                        error = "Login failed"
                    });
                }

                var result = await _signInManager.CheckPasswordSignInAsync(user, body.password, lockoutOnFailure: false);
                if (result.Succeeded) {
                    var principal = await _signInManager.CreateUserPrincipalAsync(user);
                    var token = new JwtSecurityToken(
                        TokenAuthOption.Issuer,
                        TokenAuthOption.Audience,
                        principal.Claims,
                        expires: DateTime.UtcNow.AddDays(30),
                        signingCredentials: TokenAuthOption.GetSigningCreds()
                    );

                    return Json(new {
                        success = true,
                        token = _tokenHandler.WriteToken(token)
                    });
                }

                return Json(new {
                    error = result.IsLockedOut ? "User is locked out" : "Login failed"
                });
            } catch (Exception ex) {
                return Json(new {
                    error = ex.ToString()
                });
            }
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.WithOrigins("http://localhost:4200")
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options => {
                // Identity made Cookie authentication the default.
                // However, we want JWT Bearer Auth to be the default.
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options => {
                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;

                // Configure JWT Bearer Auth to expect our security key
                options.TokenValidationParameters = new TokenValidationParameters {
                    LifetimeValidator        = (before, expires, token, param) => { return(expires > DateTime.UtcNow); },
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateActor            = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = TokenAuthOption.GetSigningKey(),
                    ValidAudience            = TokenAuthOption.Audience,
                    ValidIssuer = TokenAuthOption.Issuer
                };

                // We have to hook the OnMessageReceived event in order to
                // allow the JWT authentication handler to read the access
                // token from the query string when a WebSocket or
                // Server-Sent Events request comes in.
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context => {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;

                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hub"))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            services.Configure <IdentityOptions>(options => {
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
            });

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

            services.AddSignalR();

            services.AddSingleton <IUserIdProvider, UserIdProvider>();
            services.AddTransient <IItemService, ItemService>();
            services.AddTransient <IHeroService, HeroService>();
            services.AddTransient <ITiledService, TiledService>();
            services.AddTransient <ILocationService, LocationService>();
            services.AddTransient <IExploreService, ExploreService>();

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <ApplicationDbContext>(options => { options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")); })
            .AddDbContext <GameDbContext>(options => { options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")); })
            .BuildServiceProvider();

            services.AddDbContextFactory <GameDbContext>(builder => { builder.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")); });
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();

            services.AddCors();
            services.Configure <SettingsApp>(Configuration.GetSection("Settings"));

            services.AddSingleton <ConnectionMapping <String> >();

            //services.AddHostedService<TimedHostedService>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = TokenAuthOption.Issuer,

                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,

                    // установка потребителя токена
                    ValidAudience = TokenAuthOption.Audience,

                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true,

                    // установка ключа безопасности
                    IssuerSigningKey = TokenAuthOption.GetSymmetricSecurityKey(),

                    // ClockSkew = TokenAuthOption.ExpiresSpan
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = (context) =>
                    {
                        if (context.Request.Path.ToString().StartsWith("/api/notifications") && !context.Request.Headers.Where(w => w.Key == "Authorization").Any())
                        {
                            context.Request.Headers.Add("Authorization", context.Request.Query["token"]);
                        }

                        return(Task.CompletedTask);
                    },
                };
            });


            services.AddDbContext <DataBaseContext>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // services.AddSingleton<IAuthorizationHandler, ExperienceHandler>();
            // ClaimsPrincipal User = new ClaimsPrincipal;
            //Func<IServiceProvider, IPrincipal> getPrincipal = (sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;



            //services.AddScoped(typeof(Func<IPrincipal>), getPrincipal);

            //services.AddScoped <IPrincipal, ClaimsPrincipal>();

            services.AddScoped <IRatingRepository, VedKafManager>();

            services.AddMemoryCache();

            services.AddMvc().AddXmlSerializerFormatters();
        }