示例#1
0
 void loadSecret()
 {
     using (UserDBContext db = new UserDBContext()) {
         JwtSecret jDb = db.JwtSecret.Find(ConstR.SecretID);
         if (jDb == null)
         {
             throw new AngleX.CustomException("jwt配置异常");
         }
         jwtS = jDb;
     }
 }
示例#2
0
 void refreshDB()
 {
     using (UserDBContext db = new UserDBContext()) {
         JwtSecret jDb = db.JwtSecret.Find(ConstR.SecretID);
         if (jDb == null)
         {
             throw new AngleX.CustomException("jwt配置异常");
         }
         jDb.RefreshTime   = DateTime.Now;
         jDb.SecretPre     = jDb.SecretCurrent;
         jDb.SecretCurrent = UJwtHelper.getRandStringEx(ConstR.SecretLength);
         db.Entry <JwtSecret>(jDb).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
         db.SaveChanges();
     }
 }
示例#3
0
        /// <summary>加载时触发</summary>
        protected override void OnLoaded()
        {
#if __CORE__
            if (StartPage.IsNullOrEmpty())
            {
                StartPage =
                    // 避免出现生成 "/Admin/Admin/Index/Main" 这样的情况
                    //NewLife.Web.HttpContext.Current?.Request.PathBase.ToString().EnsureEnd("/") +
                    "/Admin/Index/Main";
            }
#else
            if (StartPage.IsNullOrEmpty())
            {
                StartPage = System.Web.HttpRuntime.AppDomainAppVirtualPath.EnsureEnd("/") + "Admin/Index/Main";
            }
#endif

            var web = Runtime.IsWeb;

            //if (AvatarPath.IsNullOrEmpty()) AvatarPath = web ? "..\\Avatars" : "Avatars";
            if (DefaultRole.IsNullOrEmpty() || DefaultRole == "3")
            {
                DefaultRole = "普通用户";
            }

            if (JwtSecret.IsNullOrEmpty() || JwtSecret.Split(':').Length != 2)
            {
                JwtSecret = $"HS256:{Rand.NextString(16)}";
            }

            // 取版权信息
            if (Copyright.IsNullOrEmpty())
            {
                var asm = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
                if (asm != null)
                {
                    var att = asm.GetCustomAttribute <AssemblyCopyrightAttribute>();
                    if (att != null)
                    {
                        Copyright = att.Copyright;
                    }
                }
            }

            base.OnLoaded();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddAutoMapper();

            var appSettingsSection = Configuration.GetSection("AppSettings");

            appSettingsSection["Secret"] = JwtSecret.Generate();
            services.Configure <AppSettings>(appSettingsSection);



            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.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
                };
            });

            services.AddScoped <IUserService, UserService>();
        }
示例#5
0
 public JwtMiddleware(RequestDelegate next, IOptions <JwtSecret> appSettings)
 {
     _next      = next;
     _jwtSecret = appSettings.Value;
 }
示例#6
0
 public RegisterCommandHandler(IUserRepository userRepository, IOptions <JwtSecret> jwtSecret)
 {
     _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
     _jwtSecret      = jwtSecret.Value ?? throw new ArgumentNullException(nameof(jwtSecret));
 }
示例#7
0
 public AuthenticateQueryHandler(IUserRepository userRepository, IOptions <JwtSecret> jwtSecret)
 {
     _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
     _jwtSecret      = jwtSecret.Value ?? throw new ArgumentNullException(nameof(jwtSecret));
 }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(@".\Resources\"));

            services.AddCors();
            services.AddControllers(options =>
            {
                options.EnableEndpointRouting = true;
                options.Filters.Add <ErrorHandlingFilterAttribute>();
            })
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                                                          factory.Create(typeof(ValidatorMessages));
            })
            .AddNewtonsoftJson();

            // SQL Server.
            services.AddDbContext <GamificationDbContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("DataConnection")));

            // SQLite.
            // services.AddDbContext<GamificationDbContext>(
            //     options => options.UseSqlite(Configuration.GetConnectionString("DataConnection_SQLite")));

            // configure DI for application services
            services.AddTransient <IUnitOfWork, UnitOfWork>();
            services.AddTransient <ContextInitializer>();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();
            services.AddTransient <IPasswordHasher, PasswordHasher>();
            services.AddTransient <IRefreshTokenProvider, RefreshTokenProvider>();
            services.AddTransient(typeof(ICacheManager <>), typeof(CacheManager <>));

            // Settings
            var jwtSecret = new JwtSecret(Configuration);

            services.AddScoped <IJwtSecret, JwtSecret>(s => jwtSecret);
            services.AddScoped <IEmailSenderSettings, EmailSenderSettings>();
            services.AddScoped <IResetPasswordSettings, ResetPasswordSettings>();

            // Services
            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IAchievementService, AchievementService>();
            services.AddScoped <IFileService, FileService>();
            services.AddScoped <IEventService, EventService>();
            services.AddScoped <IUserAchievementService, UserAchievementService>();
            services.AddScoped <IThankService, ThankService>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <IRequestAchievementService, RequestAchievementService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <IRequestOrderService, RequestOrderService>();

            // Repositories
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IAchievementRepository, AchievementRepository>();
            services.AddTransient <IFileRepository, FileRepository>();
            services.AddTransient <IEventRepository, EventRepository>();
            services.AddTransient <IUserAchievementRepository, UserAchievementRepository>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IThankRepository, ThankRepository>();
            services.AddTransient <IRequestAchievementRepository, RequestAchievementRepository>();
            services.AddTransient <IOrderRepository, OrderRepository>();
            services.AddTransient <ICategoryRepository, CategoryRepository>();
            services.AddTransient <IRequestOrderRepository, RequestOrderRepository>();

            // Validators
            services.AddTransient <IValidator <CreateUserModel>, CreateUserModelValidator>();
            services.AddTransient <IValidator <UpdateFullUserModel>, UpdateFullUserModelValidator>();
            services.AddTransient <IValidator <UpdateUserModel>, UpdateUserModelValidator>();
            services.AddTransient <IValidator <CreateAchievementModel>, CreateAchievementModelValidator>();
            services.AddTransient <IValidator <UpdateAchievementModel>, UpdateAchievementModelValidator>();
            services.AddTransient <IValidator <CreateThankModel>, CreateThankModelValidator>();
            services.AddTransient <IValidator <ResetPasswordModel>, ResetPasswordModelValidator>();
            services.AddTransient <IValidator <RequestResetPasswordModel>, RequestResetPasswordModelValidator>();
            services.AddTransient <IValidator <CreateRequestAchievementModel>, CreateRequestAchievementModelValidator>();
            services.AddTransient <IValidator <ChangePasswordModel>, ChangePasswordModelValidator>();
            services.AddTransient <IValidator <PagingInfo>, PagingInfoValidator>();
            services.AddTransient <IValidator <CreateOrderModel>, CreateOrderModelValidator>();
            services.AddTransient <IValidator <UpdateOrderModel>, UpdateOrderModelValidator>();
            services.AddTransient <IValidator <CreateCategoryModel>, CreateCategoryModelValidator>();
            services.AddTransient <IValidator <UpdateCategoryModel>, UpdateCategoryModelValidator>();
            services.AddTransient <IValidator <CreateRequestOrderModel>, CreateRequestOrderModelValidator>();

            // AutoMapper
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // Cache
            services.AddDistributedMemoryCache();

            // configure jwt authentication
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = new SymmetricSecurityKey(jwtSecret.Secret),
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

            services.AddAuthorization();

            // Swagger configuration
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Gamification", Version = "0.0.0.1"
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "Example: \"Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header
                        },
                        new List <string>()
                    }
                });
            });
        }