Idea error:程序包javax.servlet.http不存在
1.idea 初始配置的tomcat7,配置spring boot项目启动失败,单个controller都启动失败,原因是idea内置tomcat7,会失败 2.idea需要配置tomcat8.然后加载依赖关系 a. idea项目左上角,file-->project structure 配置依赖 b.点击libraries 右侧有一个加号点击然后添加 c.找到tomcat lib文件夹,依赖lib文件夹即可 from:https://blog.csdn.net/qq_33919114/article/details/79232774
View Details点击劫持漏洞:使用X-Frame-Options 解决方法(应用tomcat)
发现项目中存在 X-Frame-Options 低危漏洞: 使用 X-Frame-Options X-Frame-Options 有三个值: DENY 表示该页面不允许在 frame 中展示,即便是在相同域名的页面中嵌套也不允许。 SAMEORIGIN 表示该页面可以在相同域名页面的 frame 中展示。 ALLOW-FROM uri 表示该页面可以在指定来源的 frame 中展示。 换一句话说,如果设置为 DENY,不光在别人的网站 frame 嵌入时会无法加载,在同域名页面中同样会无法加载。 另一方面,如果设置为 SAMEORIGIN,那么页面就可以在同域名页面的 frame 中嵌套。 配置 Apache 配置 Apache 在所有页面上发送 X-Frame-Options 响应头,需要把下面这行添加到 'site' 的配置中:
1 |
Header always append X-Frame-Options SAMEORIGIN |
配置 nginx 配置 nginx 发送 X-Frame-Options 响应头,把下面这行添加到 'http', 'server' 或者 'location' 的配置中:
1 |
add_header X-Frame-Options SAMEORIGIN; |
配置 IIS 配置 IIS 发送 X-Frame-Options 响应头,添加下面的配置到 Web.config 文件中:
1 2 3 4 5 6 7 8 9 10 11 |
<system.webServer> ... <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="SAMEORIGIN" /> </customHeaders> </httpProtocol> ... </system.webServer> |
配置 TOMCAT “点击劫持:X-Frame-Options未配置” 因为项目使用的是tomcat服务器,我们不可能在每个页面去添加:
1 |
response.addHeader("x-frame-options","SAMEORIGIN"); |
因此我们使用过滤器,代码如下:
1 2 |
HttpServletResponse response = (HttpServletResponse) sResponse; response.addHeader("x-frame-options","SAMEORIGIN"); |
通过以下配置,好像就没有在扫描出来该漏洞信息。 你配不上自己的野心 也辜负了所受的苦难 from:https://www.cnblogs.com/wdnnccey/p/6476518.html
View Detailsgit清除本地账户
删除保存在本地的git账户
1 |
git credential-manager uninstall |
缓存账户
1 |
git config --global credential.helper wincred |
from:https://blog.csdn.net/big_sea_m/article/details/85341821
View DetailsJava Web项目漏洞:检测到目标URL存在http host头攻击漏洞解决办法
背景 项目上线之后使用绿盟或Acunetix安全扫描工具扫描后发现了头攻击漏洞。截图如下: 漏洞提示 检测工具在检测出漏洞后给予的提示为: 大意为不要使用request中的serverName,也就是说host header可能会在攻击时被篡改,依赖request的方法是不可靠的,形如JSP头部中的:
1 2 |
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; |
这样的使用方法就会被漏洞检测工具查出来,认定有头攻击漏洞。 解决办法 提示中说,如果是php的话不要用_SERVER[“HTTP_HOST”],apache和Nginx通过设置虚拟机来纪要非法header,而web开发中常见的运行容器就是tomcat,网络查找出的解决方案大多不适用,最后,我们找到了一个折中的办法。 主要解决办法,就是在请求拦截上面做host合法性校验,拦截掉非法请求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class SessionFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // 头攻击检测 String requestHost = request.getHeader("host"); if (requestHost != null && !ServerWhiteListUtil.isWhite(requestHost)) { response.setStatus(403); return; } ... } } |
上述代码是常见的web系统拦截器doFilter方法,我们在方法开始的地方做host判定,如果不在白名单内,则返回403状态码。漏洞工具收到403后认为访问请求已被终止,就不会报错了。 其中,ServerWhiteListUtil.isWhite(requestHost))方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package ...; import java.io.InputStreamReader; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * 服务器白名单列表 */ public class ServerWhiteListUtil { private static List<String> whiteList = null;; static { try { // 读取白名单列表 whiteList = new Gson().fromJson( new InputStreamReader(ServerWhiteListUtil.class.getResourceAsStream("/serverWhiteList.json")), new TypeToken<List<String>>() { }.getType()); } catch (Exception e) { e.printStackTrace(); } } /** * 判断当前host是否在白名单内 * @param host 待查host * @return boolean 是否在白名单内 */ public static boolean isWhite(String host) { if (whiteList == null || whiteList.size() == 0) { return true; } for (String str : whiteList) { if (str != null && str.equals(host)) { return true; } } return false; } } |
配置项serverWhiteList.json文件(放置在src根目录或resource配置目录,根据项目框架来定):
1 2 3 4 |
[ "www.aaa.com:78", "www.bbb.com:178" ] |
from:https://blog.csdn.net/ahuyangdong/article/details/79091699
View DetailsAsp.Net Core连接多个数据库
1.首先要有对应的context实体类, 多个实体类的构造函数的参数都应该是集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class firstContext : DbContext { //多个数据库应该使用这个构造函数,参数是上下文的集合 public GalpOnlineContext(DbContextOptions<firstContext> options) : base(options) { } //自定义DbContext实体属性名与数据库表对应名称(默认 表名与属性名对应是 User与Users) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable("user"); modelBuilder.Entity<Project>().ToTable("project"); //相关表名称的和类的对应 base.OnModelCreating(modelBuilder); } public DbSet<User> User { get; set; } //.... //第二种方法,重载父级的构造函数,和配置,这个只能是一个数据库时候的构造函数 /* public firstContext(DbContextOptions options) : base(options) { // Using the default constructor }*/ } } |
2.在appsettings.json中进行配置数据库连接的信息
1 2 3 4 5 6 7 8 9 10 |
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "firstContext": "Server=localhost;database=test;uid=root;pwd=123456;sslmode=none", "secondContext": "Server=localhost;database=test2;uid=root;pwd=123456;sslmode=none" }, |
3.在startup.cs文件中注册数据库上下文的信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // options.CheckConsentNeeded = context => false;实现session,默认是true options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); //注册数据库的服务 string connectionString = Configuration.GetConnectionString("firstContext"); string connectionString2 = Configuration.GetConnectionString("secondContext"); services.AddDbContext<firstContext>(options => options.UseMySql(connectionString)); services.AddDbContext<secondContext>(options => options.UseMySql(connectionString2)); //注册session services.AddDistributedMemoryCache(); services.AddSession(Options => { Options.IdleTimeout = TimeSpan.FromSeconds(1000); Options.Cookie.HttpOnly = true; }); //services.AddMemoryCache();//使用本地缓存必须添加 //注册mvc服务 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } |
然后就可以了,在使用的地方引入上下文就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class TestController : Controller { public readonly firstContext _context; //构造函数,依赖注入数据库上下文就可以了 public TestController(firstContext context) { _context = context; } public ActionResult Index(string page) { List<Project> projects = _context.Project.ToList(); ViewBag.projects = projects; return View(); } } |
from:https://www.cnblogs.com/xuqp/p/9707469.html
View DetailsAsp.Net Core 使用中间件拦截请求和返回数据,并对数据进行加密解密
GitHub demo https://github.com/zhanglilong23/Asp.NetCore.Demo 本项目使用中间件拦截请求数据,并对请求数据解密。 访问接口成功后拦截返回数据,然后将返回数据加密后返回。 其中log4net部分不再赘述(demo中有介绍) 将Post方法中Body中的数据进行AES解密 将返回数据进行AES加密 1:自定义中间件,并默认实现Invoke方法. 附带使用日志记录错误和访问时间等,写的比较糙。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
public class HttpContextMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; /// <summary> /// 计时器 /// </summary> private Stopwatch _stopwatch; //加密解密key private readonly string securitykey = "0123456789abcdef"; /// <summary> /// 构造 Http 请求中间件 /// </summary> /// <param name="next"></param> /// <param name="loggerFactory"></param> /// <param name="cacheService"></param> public HttpContextMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) { _next = next; _logger = loggerFactory.CreateLogger<HttpContextMiddleware>(); } /// <summary> /// 1:将Post方法中Body中的数据进行AES解密 /// 2:将返回数据进行AES加密 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { context.Request.EnableBuffering(); _stopwatch = new Stopwatch(); _stopwatch.Start(); _logger.LogInformation($"Handling request: " + context.Request.Path); var api = new ApiRequestInputViewModel { HttpType = context.Request.Method, Query = context.Request.QueryString.Value, RequestUrl = context.Request.Path, RequestName = "", RequestIP = context.Request.Host.Value }; var request = context.Request.Body; var response = context.Response.Body; try { using (var newRequest = new MemoryStream()) { //替换request流 context.Request.Body = newRequest; using (var newResponse = new MemoryStream()) { //替换response流 context.Response.Body = newResponse; using (var reader = new StreamReader(request)) { //读取原始请求流的内容 api.Body = await reader.ReadToEndAsync(); if (string.IsNullOrEmpty(api.Body)) await _next.Invoke(context); //示例加密字符串,使用 AES-ECB-PKCS7 方式加密,密钥为:0123456789abcdef // 加密参数:{"value":"哈哈哈"} // 加密后数据: oedwSKGyfLX8ADtx2Z8k1Q7+pIoAkdqllaOngP4TvQ4= api.Body = SecurityHelper.AESDecrypt(api.Body, securitykey); } using (var writer = new StreamWriter(newRequest)) { await writer.WriteAsync(api.Body); await writer.FlushAsync(); newRequest.Position = 0; context.Request.Body = newRequest; await _next(context); } using (var reader = new StreamReader(newResponse)) { newResponse.Position = 0; api.ResponseBody = await reader.ReadToEndAsync(); if (!string.IsNullOrWhiteSpace(api.ResponseBody)) { api.ResponseBody = SecurityHelper.AESEncrypt(api.ResponseBody, securitykey); } } using (var writer = new StreamWriter(response)) { await writer.WriteAsync(api.ResponseBody); await writer.FlushAsync(); } } } } catch (Exception ex) { _logger.LogError($" http中间件发生错误: " + ex.ToString()); } finally { context.Request.Body = request; context.Response.Body = response; } // 响应完成时存入缓存 context.Response.OnCompleted(() => { _stopwatch.Stop(); api.ElapsedTime = _stopwatch.ElapsedMilliseconds; _logger.LogDebug($"RequestLog:{DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next(0, 10000)}-{api.ElapsedTime}ms", $"{JsonConvert.SerializeObject(api)}"); return Task.CompletedTask; }); _logger.LogInformation($"Finished handling request.{_stopwatch.ElapsedMilliseconds}ms"); } } |
2:实现中间件扩展
1 2 3 4 5 6 7 |
public static class MiddlewareExtensions { public static IApplicationBuilder UseHttpContextMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<HttpContextMiddleware>(); } } |
3:在Startup使用中间件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpContextMiddleware(); //引入自定义的HtppContextMiddleware中间件 loggerFactory.AddLog4Net(); //引入log4net app.UseHttpsRedirection(); app.UseMvc(); } |
from:https://blog.csdn.net/a123_z/article/details/94011395
View Details.Net Core api 中获取应用程序物理路径wwwroot
如果要得到传统的ASP.Net应用程序中的相对路径或虚拟路径对应的服务器物理路径,只需要使用使用Server.MapPath()方法来取得Asp.Net根目录的物理路径,如下所示:
1 2 3 4 5 6 7 8 9 10 |
// Classic ASP.NET public class HomeController : Controller { public ActionResult Index() { string physicalWebRootPath = Server.MapPath("~/"); return Content(physicalWebRootPath); } } |
但是在ASPNET Core中不存在Server.MapPath()方法,Controller基类也没有Server属性。 在Asp.Net Core中取得物理路径: 从ASP.NET Core RC2开始,可以通过注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; namespace AspNetCorePathMapping { public class HomeController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public ActionResult Index() { string webRootPath = _hostingEnvironment.WebRootPath; //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Web\wwwroot string contentRootPath = _hostingEnvironment.ContentRootPath; //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Web return Content(webRootPath + "\n" + contentRootPath); } } } |
ASP.NET Core RC1 在ASP.NET Core RC2之前 (就是ASP.NET Core RC1或更低版本),通过 IApplicationEnvironment.ApplicationBasePath 来获取 Asp.Net Core应用程序的根目录(物理路径) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using Microsoft.AspNet.Mvc; using Microsoft.Extensions.PlatformAbstractions; namespace AspNetCorePathMapping { public class HomeController : Controller { private readonly IApplicationEnvironment _appEnvironment; public HomeController(IApplicationEnvironment appEnvironment) { _appEnvironment = appEnvironment; } public ActionResult Index() { return Content(_appEnvironment.ApplicationBasePath); } } } |
from:https://www.cnblogs.com/gygtech/p/9909222.html
View Detailsspringboot+thymeleaf后端设置全局变量前端js接收
公司旧的项目用play,新的项目改用springboot,前端同学问我,新的项目怎么拿baseUrl? 其实springboot+thymeleaf是可以做到的,我就贴个代码记录一下吧 后端代码如下:
1 2 3 4 5 6 7 8 9 |
@Resource private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) { if(viewResolver != null) { Map<String, Object> vars = Maps.newHashMap(); vars.put("picUrl", env.getProperty("picUrl")); vars.put("baseUrl", env.getProperty("baseUrl")); viewResolver.setStaticVariables(vars); } } |
只要放在spring能扫描到的地方就可以了. 不过这里有个问题,一般来说,这些地址都是通过properties文件,或者yml文件,分环境配置的,要拿配置文件的值,我第一时间就想用@value,但是由于加载顺序的关系,@value加载在后面,所以这里就不能用@value了,用environment
1 2 |
@Resource private Environment env; |
然后到前端的代码: 把这段代码放到header.html,统一加载就行了
1 2 3 4 |
<script th:inline="javascript"> const baseUrl = '[(${baseUrl})]'; const picUrl = '[(${picUrl})]'; </script> |
from:https://blog.csdn.net/bear_lam/article/details/80278590
View DetailsSpringBoot2.x过后static下的静态资源无法访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.example.thymeleaf.commons; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置静态资源映射 * * @author sunziwen * @version 1.0 * @date 2018-11-16 14:57 **/ @Component public class WebMvcConfig implements WebMvcConfigurer { /** * 添加静态资源文件,外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } } |
from:https://blog.csdn.net/wenxingchen/article/details/84139845
View Details