public AccountController(
     UserManager <User> userManager,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration)
 {
     _userManager           = userManager;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #2
0
 public LoginHandler(IUserService userService, IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
                     IUnitOfWork unitOfWork)
 {
     _userService           = userService;
     _unitOfWork            = unitOfWork;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #3
0
        private void ConfigureSecurity(IServiceCollection services, JwtTokenConfiguration jwtTokenConfiguration)
        {
            services.AddSingleton(jwtTokenConfiguration);
            services.AddSingleton <IJwtTokenGenerator, JwtTokenGenerator>();

            services.AddAuthentication(authenticationOptions =>
            {
                authenticationOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authenticationOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.RequireHttpsMetadata      = true;
                jwtBearerOptions.SaveToken                 = true;
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = jwtTokenConfiguration.Claims.Issuer,

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfiguration.Secret)),

                    ValidAudience    = jwtTokenConfiguration.Claims.Audience,
                    ValidateAudience = true,

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });
        }
Пример #4
0
 public AccountController(
     IOptions <JwtTokenConfiguration> configuration,
     UserManager <IdentityUser> userManager,
     JwtSecurityTokenHandler tokenHandler)
 {
     _userManager   = userManager;
     _tokenHandler  = tokenHandler;
     _configuration = configuration.Value;
 }
 public RefreshTokenCommandHandler(IRefreshTokenRepository tokenRepository, IMapper mapper, ISender sender,
                                   IUserRepository userRepository, IOptions <JwtTokenConfiguration> tokenConfiguration)
 {
     _tokenRepository    = tokenRepository;
     _mapper             = mapper;
     _sender             = sender;
     _userRepository     = userRepository;
     _tokenConfiguration = tokenConfiguration.Value;
 }
Пример #6
0
 public AccountController(
     UserManager <User> userManager,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
     IPermissionAppService permissionAppService)
 {
     _userManager           = userManager;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
     _permissionAppService  = permissionAppService;
 }
Пример #7
0
 public AccountController(
     UserManager <User> userManager,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
     IConfiguration configuration,
     SmtpClient smtpClient)
 {
     _userManager           = userManager;
     _configuration         = configuration;
     _smtpClient            = smtpClient;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #8
0
 public AccountController(
     IAuthenticationAppService authenticationAppService,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
     IConfiguration configuration,
     IEmailSender emailSender)
 {
     _authenticationAppService = authenticationAppService;
     _configuration            = configuration;
     _emailSender           = emailSender;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #9
0
 public LoginCommandHandler(IMapper mapper, ISender sender, IUserRepository userRepository,
                            IOptions <JwtTokenConfiguration> tokenConfiguration, IRefreshTokenRepository tokenRepository,
                            IPasswordHasher <UserDto> hasher)
 {
     _mapper             = mapper;
     _sender             = sender;
     _userRepository     = userRepository;
     _tokenRepository    = tokenRepository;
     _hasher             = hasher;
     _tokenConfiguration = tokenConfiguration.Value;
 }
Пример #10
0
 public UserService
 (
     IOptions <JwtTokenConfiguration> appSettings,
     UserManager <User> userManager,
     IHttpContextAccessor contextAccessor,
     ApplicationDbContext context
 )
 {
     _jwtToken        = appSettings.Value;
     _userManager     = userManager;
     _contextAccessor = contextAccessor;
     _context         = context;
 }
Пример #11
0
 public UserLogic(
     UserManager <User> userManager,
     IMapper mapper,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
     IConfiguration configuration,
     ILogger <UserLogic> logger)
 {
     _UserManager           = userManager;
     _Mapper                = mapper;
     _configuration         = configuration;
     _logger                = logger;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #12
0
 public AccountController(
     UserManager <User> userManager,
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration,
     IConfiguration configuration,
     SmtpClient smtpClient,
     ILogger <AccountController> logger,
     IUserAppService userAppService)
 {
     _userManager           = userManager;
     _configuration         = configuration;
     _smtpClient            = smtpClient;
     _logger                = logger;
     _userAppService        = userAppService;
     _jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = JwtTokenConfiguration.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = JwtTokenConfiguration.Audience,
                    ValidateLifetime = true,

                    IssuerSigningKey         = JwtTokenConfiguration.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddMvc();
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Graduate Work API", Version = "v1"
                });
            });
            services.AddSwaggerGen(sg =>
            {
                {
                    sg.AddSecurityDefinition("Bearer",
                                             new ApiKeyScheme()
                    {
                        In          = "header",
                        Description = "Please insert JWT with Bearer into field",
                        Name        = "Authorization",
                        Type        = "apiKey"
                    });
                };
                var basePath = AppContext.BaseDirectory;
                var xmlPath  = Path.Combine(basePath, "GraduateWorkApi.xml");
                sg.IncludeXmlComments(xmlPath);
            });

            RegisterTypes(services);
        }
Пример #14
0
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;

            _signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));

            _jwtTokenConfiguration = new JwtTokenConfiguration
            {
                Issuer             = _configuration["Authentication:JwtBearer:Issuer"],
                Audience           = _configuration["Authentication:JwtBearer:Audience"],
                SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256),
                StartDate          = DateTime.UtcNow,
                EndDate            = DateTime.UtcNow.AddDays(60),
            };
        }
Пример #15
0
        public ReadTokenMiddleware(RequestDelegate next, JwtTokenConfiguration tokenConfiguration)
        {
            _next = next;

            this.Securized = tokenConfiguration.AllApisAreSecurized;
            if (this.Securized)
            {
                try
                {
                    this._jwtTokenManager = new JwtTokenManager(tokenConfiguration);
                }
                catch (System.Exception e)
                {
                    Trace.WriteLine(e.Message);
                    throw;
                }
            }
        }
Пример #16
0
        public JwtSecurityToken GenerateJwtTokenAsync(Guid userId)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, userId.ToString()),
            };

            var identity = new ClaimsIdentity
                               (claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            return(new JwtSecurityToken(
                       issuer: JwtTokenConfiguration.Issuer,
                       audience: JwtTokenConfiguration.Audience,
                       notBefore: DateTime.UtcNow,
                       claims: identity.Claims,
                       expires: DateTime.UtcNow.Add(TimeSpan.FromDays(JwtTokenConfiguration.LifeTime)),
                       signingCredentials: new SigningCredentials(JwtTokenConfiguration.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
        }
        public static void ConfigureJwtTokenAuth(this IServiceCollection services, IConfiguration configuration)
        {
            _signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"]));

            _jwtTokenConfiguration = new JwtTokenConfiguration
            {
                Issuer             = configuration["Authentication:JwtBearer:Issuer"],
                Audience           = configuration["Authentication:JwtBearer:Audience"],
                SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256),
                StartDate          = DateTime.UtcNow,
                EndDate            = DateTime.UtcNow.AddHours(1),
            };

            services.Configure <JwtTokenConfiguration>(config =>
            {
                config.Audience           = _jwtTokenConfiguration.Audience;
                config.EndDate            = _jwtTokenConfiguration.EndDate;
                config.Issuer             = _jwtTokenConfiguration.Issuer;
                config.StartDate          = _jwtTokenConfiguration.StartDate;
                config.SigningCredentials = _jwtTokenConfiguration.SigningCredentials;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateActor            = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = _jwtTokenConfiguration.Issuer,
                    ValidAudience    = _jwtTokenConfiguration.Audience,
                    IssuerSigningKey = _signingKey
                };
            });
        }
Пример #18
0
        /// <summary>
        /// Method for add authentication.
        /// </summary>
        /// <param name="services"><see cref="IServiceCollection"/> instance.</param>
        public static void AddAuthentication(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = JwtTokenConfiguration.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = JwtTokenConfiguration.Audience,
                    ValidateLifetime = true,

                    IssuerSigningKey         = JwtTokenConfiguration.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });
        }
Пример #19
0
 public AuthController(
     IOptions <JwtTokenConfiguration> jwtTokenConfiguration)
 {
     this._jwtTokenConfiguration = jwtTokenConfiguration.Value;
 }
Пример #20
0
 public JwtService(JwtTokenConfiguration jwtTokenConfiguration)
 {
     _jwtTokenConfiguration = jwtTokenConfiguration;
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AspNetCoreStarterKitDbContext>(options =>
                                                                  options.UseSqlServer(Configuration.GetConnectionString(AppConfig.DefaultConnection))
                                                                  .UseLazyLoadingProxies());

            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <AspNetCoreStarterKitDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthorization(options =>
            {
                foreach (var permission in Permissions.GetAll())
                {
                    options.AddPolicy(permission,
                                      policy => policy.Requirements.Add(new PermissionRequirement(permission)));
                }
            });

            services.AddCors(options =>
            {
                options.AddPolicy(AppConfig.App_CorsOriginPolicyName,
                                  builder =>
                                  builder.WithOrigins(AppConfig.App_CorsOrigins
                                                      .Split(",", StringSplitOptions.RemoveEmptyEntries))
                                  .AllowAnyHeader()
                                  .AllowAnyMethod());
            });

            _signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(AppConfig.Authentication_JwtBearer_SecurityKey));

            _jwtTokenConfiguration = new JwtTokenConfiguration
            {
                Issuer             = AppConfig.Authentication_JwtBearer_Issuer,
                Audience           = AppConfig.Authentication_JwtBearer_Audience,
                SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256),
                StartDate          = DateTime.UtcNow,
                EndDate            = DateTime.UtcNow.AddDays(60),
            };

            services.Configure <JwtTokenConfiguration>(config =>
            {
                config.Audience           = _jwtTokenConfiguration.Audience;
                config.EndDate            = _jwtTokenConfiguration.EndDate;
                config.Issuer             = _jwtTokenConfiguration.Issuer;
                config.StartDate          = _jwtTokenConfiguration.StartDate;
                config.SigningCredentials = _jwtTokenConfiguration.SigningCredentials;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateActor            = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = _jwtTokenConfiguration.Issuer,
                    ValidAudience    = _jwtTokenConfiguration.Audience,
                    IssuerSigningKey = _signingKey
                };
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "WebApiBestPractices", Version = "v1"
                });
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
                    In          = ParameterLocation.Header,
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });

                options.OperationFilter <SecurityRequirementsOperationFilter>();
            });

            var mvcBuilder = services.AddControllers(options =>
            {
                options.Filters.AddService <UnitOfWorkActionFilter>();
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            LoadModules(mvcBuilder);

            services.Configure <EmailSettings>(Configuration.GetSection(AppConfig.Email_Smtp));
            services.AddSingleton <IEmailSender, EmailSender>();
            services.ConfigureApplicationService();
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddScoped <UnitOfWorkActionFilter>();
        }
Пример #22
0
 public TokenController(IOptions <JwtTokenConfiguration> configuration)
 {
     _configuration = configuration.Value;
 }
 public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, JwtTokenConfiguration configuration)
 {
     return(AddJwtBearer(builder, JwtBearerDefaults.AuthenticationScheme, configuration));
 }
        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, JwtTokenConfiguration configuration)
        {
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration.Key));

            return(builder.AddJwtBearer(authenticationScheme,
                                        options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = key,
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                };
            },
                                        moreOptions =>
            {
                moreOptions.TokenLifeTimespan = TimeSpan.FromSeconds(configuration.AccessExpireSeconds);
                moreOptions.ClientId = configuration.ClientId;
            }
                                        ));
        }
Пример #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddIdentity <User, Role>()
            .AddDefaultTokenProviders();

            services.AddTransient <IUserStore <User>, CustomUserStore>();
            services.AddTransient <IUserEmailStore <User>, CustomUserStore>();
            services.AddTransient <IRoleStore <Role>, CustomRoleStore>();

            services.AddAuthorization(options =>
            {
                foreach (var permission in IntegratedPermissions.All())
                {
                    options.AddPolicy(permission.Name,
                                      policy => policy.Requirements.Add(new PermissionRequirement(permission)));
                }
            });

            var signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(Configuration["Authentication:JwtBearer:SecurityKey"]));

            var jwtTokenConfiguration = new JwtTokenConfiguration
            {
                Issuer             = Configuration["Authentication:JwtBearer:Issuer"],
                Audience           = Configuration["Authentication:JwtBearer:Audience"],
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                StartDate          = DateTime.UtcNow,
                EndDate            = DateTime.UtcNow.AddDays(60),
            };

            services.Configure <JwtTokenConfiguration>(config =>
            {
                config.Audience           = jwtTokenConfiguration.Audience;
                config.EndDate            = jwtTokenConfiguration.EndDate;
                config.Issuer             = jwtTokenConfiguration.Issuer;
                config.StartDate          = jwtTokenConfiguration.StartDate;
                config.SigningCredentials = jwtTokenConfiguration.SigningCredentials;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateActor            = true,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = jwtTokenConfiguration.Issuer,
                    ValidAudience    = jwtTokenConfiguration.Audience,
                    IssuerSigningKey = signingKey
                };

                jwtBearerOptions.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(_SignalRRoute)))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddCors();

            services.AddScoped <IAuthorizationHandler, PermissionHandler>();


            // Add AddRazorPages if the app uses Razor Pages.
            services.AddRazorPages().AddNewtonsoftJson();

            //Adds signalr
            services.AddSignalR();

            services.AddAutoMapper(typeof(Startup));

            // Generate swagger file
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ProductOwnerSimGame API", Version = "v1"
                });

                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
                    In          = ParameterLocation.Header,
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });

                options.OperationFilter <SecurityRequirementsOperationFilter>();
            });
            services.AddSwaggerGenNewtonsoftSupport();

            // Data access
            //var cosmosDbConnectionString = "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
            var cosmosDbConnectionString = Configuration["Database:ConnectionString"];

            services.AddSingleton <IGameDataAccess>(srv => new GameDataAccessCosmosDb(cosmosDbConnectionString));
            services.AddSingleton <IGameVariantDataAccess>(srv => new GameVariantDataAccessCosmosDb(cosmosDbConnectionString));
            services.AddSingleton <IOrganizationDataAccess>(srv => new OrganizationDataAccessCosmosDb(cosmosDbConnectionString));
            services.AddSingleton <IUserDataAccess>(srv => new UserDataAccessCosmosDb(cosmosDbConnectionString));

            // Logic
            services.AddTransient <IGameLogic, GameLogic>();
            services.AddTransient <IGameViewLogic, GameViewLogic>();
            services.AddTransient <IGameVariantLogic, GameVariantLogic>();
            services.AddTransient <IOrganizationLogic, OrganizationLogic>();
            services.AddTransient <IUserLogic, UserLogic>();
            services.AddTransient <IPermissionLogic, PermissionLogic>();

            // Game controller
            services.AddSingleton <IGameManager, GameManager>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }