public async Task <IActionResult> Login([FromBody] LoginInputDto input) { //TODO: Parse to passwordHash and use as hash var user = await GetIdentity(input.Username, input.Password); if (user == null) { return(BadRequest(new { message = "Username or Password is incorrect" })); } var key = JwtConfigs.GetSecurityKey(); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(claims: user.Claims, signingCredentials: creds, expires: DateTime.UtcNow + TimeSpan.FromHours(24)); var tokenResult = new JwtSecurityTokenHandler().WriteToken(token); return(Ok(new { token = tokenResult })); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); string connectionString = @"Server=DESKTOP-D0NSBJ1\SQLEXPRESS;Database=LearningCzechDb;Trusted_Connection=True;MultipleActiveResultSets=true"; services.AddDbContext <LearningDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Scoped); //services.AddAuthorization(auth => //{ // auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() // .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) // .RequireAuthenticatedUser().Build()); //}); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = JwtConfigs.GetSecurityKey(), ValidateAudience = false, ValidateIssuer = false }; }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp"; }); services.AddScoped <IUserService, UserService>(); services.AddScoped <IWordGroupService, WordGroupService>(); services.AddScoped <IWordService, WordService>(); services.AddScoped <IArticleService, ArticleService>(); services.AddScoped <IImagesService, ImagesService>(); }
private JwtConfigs GetJwtTokenConfigs(EnvironmentModel setting, string AppCode) { DataTable dt = new DataTable(); JwtConfigs jwt = new JwtConfigs(); string conn_string = setting.DBRBAC.ConnectionString; string db_name = setting.DBRBAC.DatabaseName; string db_username = setting.DBRBAC.Username; string db_password = setting.DBRBAC.Password; string db_conn_string = string.Format(conn_string, db_name, db_username, db_password); string query = string.Format("SELECT TOP(1) * FROM SYS_JWT_TOKEN WHERE Code='{0}'", AppCode); using (var cnn = new SqlConnection(db_conn_string)) { cnn.Open(); using (var cmd = new SqlCommand(query, cnn)) { cmd.CommandText = query; cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 60; SqlDataAdapter adp = new SqlDataAdapter(cmd); adp.Fill(dt); } cnn.Close(); } if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { jwt.Secret = dr["Secret"].ToString(); jwt.Issuer = dr["Issuer"].ToString(); jwt.Audience = dr["Audience"].ToString(); jwt.Expires = Convert.ToInt32(dr["Expires"]); } } return(jwt); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // if in dev services.AddSingleton <IDataContext, MemoryDataContext>(service => CreateMockdataContext()); services.Configure <CryptoConfigs>(options => Configuration.GetSection("Crypto").Bind(options)); services.Configure <JwtConfigs>(options => Configuration.GetSection("JWT").Bind(options)); var jwtConfigs = new JwtConfigs(); Configuration.GetSection("JWT").Bind(jwtConfigs); services.AddControllersWithViews(); 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(Encoding.UTF8.GetBytes(jwtConfigs.SymmetricKey)), ValidateIssuer = false, // false for development ValidateAudience = false, // false for development ClockSkew = TimeSpan.Zero }; }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); }
public UserAccountController(IDataContext dataContext, IOptions <CryptoConfigs> cryptoSettings, IOptions <JwtConfigs> jwtSettings) { this.dataContext = dataContext; this.cryptoSettings = cryptoSettings?.Value ?? throw new ArgumentNullException(nameof(cryptoSettings), "Crypto settings are required"); this.jwtSettings = jwtSettings?.Value ?? throw new ArgumentNullException(nameof(jwtSettings), "JWT settings are required"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var cultureInfo = new CultureInfo("en-GB"); CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; EnvironmentModel EnvronmentSetting = new EnvironmentModel() { AppCodes = Configuration.GetSection("AppCode").Get <AppCode>(), DBRBAC = Configuration.GetSection("DBRBAC").Get <DBRBAC>(), }; services.AddHttpClient(); EnvronmentSetting.DBRBAC.ConnectionString = GetConnectionString( EnvronmentSetting.DBRBAC.ConnectionString, EnvronmentSetting.DBRBAC.DatabaseName, EnvronmentSetting.DBRBAC.Username, EnvronmentSetting.DBRBAC.Password); JwtConfigs jwtConfigs = GetJwtTokenConfigs(EnvronmentSetting, EnvronmentSetting.AppCodes.JwtCode); services.Configure <JwtConfigs>(Configuration.GetSection(nameof(JwtConfigs))); // services.AddSingleton<IJwtConfigs>(sp => sp.GetRequiredService<IOptions<JwtConfigs>>().Value); services.AddSingleton <IJwtConfigs>(jwtConfigs); var key = Encoding.ASCII.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(jwtConfigs.Secret))); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; // allow roles }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidIssuer = jwtConfigs.Issuer, ValidAudience = jwtConfigs.Audience, ClockSkew = TimeSpan.Zero }; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Core API", Version = "v1" }); var securityScheme = new OpenApiSecurityScheme() { Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, BearerFormat = "JWT", Scheme = "bearer" }; c.AddSecurityDefinition("Bearer", securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); }); services.AddControllers(); #region NLog Environment.SetEnvironmentVariable("ELASTICSEARCH_URL", ""); #endregion var container = new Container(); #region NLog container.UseInstance ( new LoggerFactory().AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }) ); container.Register(typeof(ILogger <>), typeof(Logger <>), Reuse.Singleton); container.Register <ILogs, Logs>(Reuse.Singleton); services.AddScoped(typeof(ILogs), typeof(Logs)); #endregion services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // Register Service services.AddScoped <IEnvironmentConfigs>(r => new EnvironmentConfigs(EnvronmentSetting)); services.AddScoped <IDashboardService, DashboardService>(); services.AddScoped <IRegisterService, RegisterService>(); services.AddScoped <IAuthService, AuthService>(); services.AddScoped <ITokenKeyService, TokenKeyService>(); services.AddScoped <IUserGroupService, UserGroupService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IFuncMenuService, FuncMenuService>(); services.AddScoped <IPermissionGroupService, PermissionGroupService>(); services.AddScoped <IPermissionRoleService, PermissionRoleService>(); services.AddScoped <IPermissionFuncService, PermissionFuncService>(); services.AddScoped <ISectionService, SectionService>(); services.AddScoped <IRoleService, RoleService>(); // Register Repository services.AddScoped <IDashboardRepository, DashboardRepository>(); services.AddScoped <IRegisterRepository, RegisterRepository>(); services.AddScoped <IAuthRepository, AuthRepository>(); services.AddScoped <ILogRepository, LogRepository>(); services.AddScoped <IOwnerRepository, OwnerRepository>(); services.AddScoped <IFuncMenuRepository, FuncMenuRepository>(); services.AddScoped <ITokenKeyRepository, TokenKeyRepository>(); services.AddScoped <IUserGroupRepository, UserGroupRepository>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IFuncMenuRepository, FuncMenuRepository>(); services.AddScoped <IPermissionGroupRepository, PermissionGroupRepository>(); services.AddScoped <IPermissionRoleRepository, PermissionRoleRepository>(); services.AddScoped <IPermissionFuncRepository, PermissionFuncRepository>(); services.AddScoped <ISectionRepository, SectionRepository>(); services.AddScoped <IRoleRepository, RoleRepository>(); }