Commit 07e071264c21f2908aec5d7a63fac595b0045b79

Authored by 王通
1 parent f7d76188

1.越权访问控制

src/main/java/com/bsth/common/Constants.java
1   -package com.bsth.common;
2   -
3   -/**
4   - *
5   - * @ClassName: Constants
6   - * @Description: TODO(常量类)
7   - * @author PanZhao
8   - * @date 2016年3月18日 下午11:06:53
9   - *
10   - */
11   -public class Constants {
12   -
13   - /**
14   - * 不需要拦截的资源
15   - */
16   - public static final String LOGIN = "/user/login/**";
17   - public static final String ORIGINAL_LOGIN_PAGE = "/login.html";
18   - public static String LOGIN_PAGE = "/login.html";
19   - public static final String ASSETS_URL = "/login_assets/**";
20   - public static final String FAVICON_URL = "/favicon.ico";
21   - public static final String LOGIN_FAILURE = "/user/loginFailure";
22   - public static final String CAPTCHA = "/captcha.jpg";
23   -
24   - // springboot manage health的检测url
25   - public static final String ACTUATOR_MANAGEMENT_HEALTH = "/manage/health";
26   - // 车辆数据同步url
27   - public static final String VEHICLE_DATA_SYNC_URL = "/dataSync/vehicle/api/**";
28   -
29   - //对外的营运数据接口
30   - public static final String SERVICE_INTERFACE = "/companyService/**";
31   -
32   - /**
33   - * 线调部分子页面不做拦截,便于浏览器缓存
34   - */
35   - public static final String XD_CHILD_PAGES = "/real_control_v2/**";
36   - public static final String XD_REAL_GPS = "/gps/real/line";
37   - //public static final String XD_TEMPS = "/pages/control/line/temps/**";
38   -
39   - //车载网关上行接口
40   - public static final String UPSTREAM_URL = "/control/upstream";
41   - //rfid 上传入口
42   - public static final String UP_RFID_URL = "/rfid/**";
43   -
44   - public static final String SESSION_USERNAME = "sessionUserName";
45   - public static final String COMPANY_AUTHORITYS = "cmyAuths";
46   - public static final String STATION_AND_SECTION_COUNT = "/station/updateStationAndSectionCode";
47   -
48   - /**
49   - * 解除调度指令和班次的外键约束
50   - */
51   - public static final String REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch=?";
52   -
53   - /**
54   - * 批量解除调度指令和班次的外键约束
55   - */
56   - public static final String MULTI_REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch in ";
57   -
58   - /**
59   - * 批量解除子任务和班次的外键约束
60   - */
61   - public static final String MULTI_REMOVE_CHILDTASK_SCH_FK = "update bsth_c_s_child_task set schedule=NULL where schedule in ";
62   -
63   - public static final String WEAK_CIPHER = "weakCipher";
64   -
65   - public static final String FILE_AUTH = "/.well-known/pki-validation/fileauth.txt";
66   -
67   - public static final String SSO_TOKEN = "ssoToken";
68   -
69   - public static final String RESOURCE_AUTHORITYS = "resourceAuthoritys";
70   -}
  1 +package com.bsth.common;
  2 +
  3 +/**
  4 + *
  5 + * @ClassName: Constants
  6 + * @Description: TODO(常量类)
  7 + * @author PanZhao
  8 + * @date 2016年3月18日 下午11:06:53
  9 + *
  10 + */
  11 +public class Constants {
  12 +
  13 + /**
  14 + * 不需要拦截的资源
  15 + */
  16 + public static final String LOGIN = "/user/login/**";
  17 + public static final String ORIGINAL_LOGIN_PAGE = "/login.html";
  18 + public static String LOGIN_PAGE = "/login.html";
  19 + public static final String ASSETS_URL = "/assets/**";
  20 + public static final String LOGIN_ASSETS_URL = "/login_assets/**";
  21 + public static final String FAVICON_URL = "/favicon.ico";
  22 + public static final String METRONIC_URL = "/metronic_v4.5.4/**";
  23 + public static final String LOGIN_FAILURE = "/user/loginFailure";
  24 + public static final String CAPTCHA = "/captcha.jpg";
  25 +
  26 + // springboot manage health的检测url
  27 + public static final String ACTUATOR_MANAGEMENT_HEALTH = "/manage/health";
  28 + // 车辆数据同步url
  29 + public static final String VEHICLE_DATA_SYNC_URL = "/dataSync/vehicle/api/**";
  30 +
  31 + //对外的营运数据接口
  32 + public static final String SERVICE_INTERFACE = "/companyService/**";
  33 +
  34 + /**
  35 + * 线调部分子页面不做拦截,便于浏览器缓存
  36 + */
  37 + public static final String XD_CHILD_PAGES = "/real_control_v2/**";
  38 + public static final String XD_REAL_GPS = "/gps/real/line";
  39 + //public static final String XD_TEMPS = "/pages/control/line/temps/**";
  40 +
  41 + //车载网关上行接口
  42 + public static final String UPSTREAM_URL = "/control/upstream";
  43 + //rfid 上传入口
  44 + public static final String UP_RFID_URL = "/rfid/**";
  45 +
  46 + public static final String SESSION_USERNAME = "sessionUserName";
  47 + public static final String COMPANY_AUTHORITYS = "cmyAuths";
  48 + public static final String STATION_AND_SECTION_COUNT = "/station/updateStationAndSectionCode";
  49 +
  50 + /**
  51 + * 解除调度指令和班次的外键约束
  52 + */
  53 + public static final String REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch=?";
  54 +
  55 + /**
  56 + * 批量解除调度指令和班次的外键约束
  57 + */
  58 + public static final String MULTI_REMOVE_DIRECTIVE_SCH_FK = "update bsth_v_directive_60 set sch=NULL where sch in ";
  59 +
  60 + /**
  61 + * 批量解除子任务和班次的外键约束
  62 + */
  63 + public static final String MULTI_REMOVE_CHILDTASK_SCH_FK = "update bsth_c_s_child_task set schedule=NULL where schedule in ";
  64 +
  65 + public static final String WEAK_CIPHER = "weakCipher";
  66 +
  67 + public static final String FILE_AUTH = "/.well-known/pki-validation/fileauth.txt";
  68 +
  69 + public static final String SSO_TOKEN = "ssoToken";
  70 +
  71 + public static final String RESOURCE_AUTHORITYS = "resourceAuthoritys";
  72 +}
... ...
src/main/java/com/bsth/entity/sys/SysUser.java
1   -package com.bsth.entity.sys;
2   -
3   -import com.fasterxml.jackson.annotation.JsonIgnore;
4   -import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
5   -import org.springframework.format.annotation.DateTimeFormat;
6   -import org.springframework.util.StringUtils;
7   -import org.joda.time.DateTime;
8   -import javax.persistence.*;
9   -import java.io.Serializable;
10   -import java.util.Date;
11   -import java.util.HashSet;
12   -import java.util.LinkedHashSet;
13   -import java.util.Set;
14   -
15   -@Entity
16   -@Table(name = "bsth_c_sys_user")
17   -@JsonIgnoreProperties(ignoreUnknown = true)
18   -@NamedEntityGraphs({
19   - @NamedEntityGraph(name = "sysUser_role", attributeNodes = {
20   - @NamedAttributeNode("roles")
21   - })
22   -})
23   -public class SysUser implements Serializable {
24   -
25   - @Id
26   - @GeneratedValue(strategy = GenerationType.IDENTITY)
27   - private Integer id;
28   -
29   - private String userName;
30   -
31   - private String name;
32   -
33   - @JsonIgnore
34   - private String password;
35   -
36   - @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
37   - private Date createDate;
38   -
39   - @Column(name = "update_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
40   - private Date updateDate;
41   -
42   - @DateTimeFormat(pattern = "yyyy-MM-dd")
43   - private Date lastLoginDate;
44   -
45   - /** 最近密码更新时间 */
46   - @DateTimeFormat(pattern = "yyyy-MM-dd")
47   - private Date lastPwdDate;
48   - /** 密码有效期 */
49   - private Integer pwdValidPeriod;
50   -
51   - private String agencies;
52   -
53   - private boolean enabled;
54   -
55   - @ManyToMany(fetch = FetchType.EAGER)
56   - private Set<Role> roles = new LinkedHashSet<>();
57   -
58   - private String jobCode;
59   -
60   - private String realName;
61   -
62   - /**
63   - * 密码过期时间
64   - */
65   - @Transient
66   - private Date pwdExpiredDate;
67   -
68   - public Integer getId() {
69   - return id;
70   - }
71   -
72   - public void setId(Integer id) {
73   - this.id = id;
74   - }
75   -
76   - public String getUserName() {
77   - return userName;
78   - }
79   -
80   - public void setUserName(String userName) {
81   - this.userName = userName;
82   - }
83   -
84   - public String getName() {
85   - return name;
86   - }
87   -
88   - public void setName(String name) {
89   - this.name = name;
90   - }
91   -
92   - public Date getCreateDate() {
93   - return createDate;
94   - }
95   -
96   - public void setCreateDate(Date createDate) {
97   - this.createDate = createDate;
98   - }
99   -
100   - public Date getUpdateDate() {
101   - return updateDate;
102   - }
103   -
104   - public void setUpdateDate(Date updateDate) {
105   - this.updateDate = updateDate;
106   - }
107   -
108   - public Date getLastLoginDate() {
109   - return lastLoginDate;
110   - }
111   -
112   - public void setLastLoginDate(Date lastLoginDate) {
113   - this.lastLoginDate = lastLoginDate;
114   - }
115   -
116   - public String getAgencies() {
117   - return agencies;
118   - }
119   -
120   - public void setAgencies(String agencies) {
121   - this.agencies = agencies;
122   - }
123   -
124   - public boolean isEnabled() {
125   - return enabled;
126   - }
127   -
128   - public void setEnabled(boolean enabled) {
129   - this.enabled = enabled;
130   - }
131   -
132   - public String getPassword() {
133   - return password;
134   - }
135   -
136   - public void setPassword(String password) {
137   - this.password = password;
138   - }
139   -
140   - public Set<Role> getRoles() {
141   - return roles;
142   - }
143   -
144   - public void setRoles(Set<Role> roles) {
145   - this.roles = roles;
146   - }
147   -
148   - public String getJobCode() {
149   - return jobCode;
150   - }
151   -
152   - public void setJobCode(String jobCode) {
153   - this.jobCode = jobCode;
154   - }
155   -
156   - public String getRealName() {
157   - return realName;
158   - }
159   -
160   - public void setRealName(String realName) {
161   - this.realName = realName;
162   - }
163   -
164   - public Set<String> getLinks() {
165   - Set<String> links = new HashSet<>();
166   - if (links.size() == 0) {
167   - for (Role role : roles) {
168   - for (Module module : role.getModules()) {
169   - String symbol = module.getMappSymbol();
170   - if (!StringUtils.isEmpty(symbol)) {
171   - String[] symbols = symbol.split(";");
172   - for (String temp : symbols) {
173   - if (!StringUtils.isEmpty(temp)) {
174   - links.add(temp);
175   - }
176   - }
177   - }
178   - }
179   - }
180   - }
181   -
182   - return links;
183   - }
184   -
185   - public Date getLastPwdDate() {
186   - return lastPwdDate;
187   - }
188   -
189   - public void setLastPwdDate(Date lastPwdDate) {
190   - this.lastPwdDate = lastPwdDate;
191   - }
192   -
193   - public Integer getPwdValidPeriod() {
194   - return pwdValidPeriod;
195   - }
196   -
197   - public void setPwdValidPeriod(Integer pwdValidPeriod) {
198   - this.pwdValidPeriod = pwdValidPeriod;
199   - }
200   -
201   - public Date getPwdExpiredDate() {
202   - DateTime dateTime = new DateTime(getLastPwdDate());
203   - if (pwdValidPeriod != null) {
204   - dateTime = dateTime.plusDays(pwdValidPeriod);
205   - }
206   -
207   - return dateTime.toDate();
208   - }
209   -
210   - public void setPwdExpiredDate(Date pwdExpiredDate) {
211   - this.pwdExpiredDate = pwdExpiredDate;
212   - }
213   -}
  1 +package com.bsth.entity.sys;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonIgnore;
  4 +import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  5 +import org.springframework.format.annotation.DateTimeFormat;
  6 +import org.springframework.util.StringUtils;
  7 +import org.joda.time.DateTime;
  8 +import javax.persistence.*;
  9 +import java.io.Serializable;
  10 +import java.util.Date;
  11 +import java.util.HashSet;
  12 +import java.util.LinkedHashSet;
  13 +import java.util.Set;
  14 +
  15 +@Entity
  16 +@Table(name = "bsth_c_sys_user")
  17 +@JsonIgnoreProperties(ignoreUnknown = true)
  18 +@NamedEntityGraphs({
  19 + @NamedEntityGraph(name = "sysUser_role", attributeNodes = {
  20 + @NamedAttributeNode("roles")
  21 + })
  22 +})
  23 +public class SysUser implements Serializable {
  24 +
  25 + @Id
  26 + @GeneratedValue(strategy = GenerationType.IDENTITY)
  27 + private Integer id;
  28 +
  29 + private String userName;
  30 +
  31 + private String name;
  32 +
  33 + @JsonIgnore
  34 + private String password;
  35 +
  36 + @Column(updatable = false, name = "create_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
  37 + private Date createDate;
  38 +
  39 + @Column(name = "update_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  40 + private Date updateDate;
  41 +
  42 + @DateTimeFormat(pattern = "yyyy-MM-dd")
  43 + private Date lastLoginDate;
  44 +
  45 + /** 最近密码更新时间 */
  46 + @DateTimeFormat(pattern = "yyyy-MM-dd")
  47 + private Date lastPwdDate;
  48 + /** 密码有效期 */
  49 + private Integer pwdValidPeriod;
  50 +
  51 + private String agencies;
  52 +
  53 + private boolean enabled;
  54 +
  55 + @ManyToMany(fetch = FetchType.EAGER)
  56 + private Set<Role> roles = new LinkedHashSet<>();
  57 +
  58 + private String jobCode;
  59 +
  60 + private String realName;
  61 +
  62 + /**
  63 + * 密码过期时间
  64 + */
  65 + @Transient
  66 + private Date pwdExpiredDate;
  67 +
  68 + public Integer getId() {
  69 + return id;
  70 + }
  71 +
  72 + public void setId(Integer id) {
  73 + this.id = id;
  74 + }
  75 +
  76 + public String getUserName() {
  77 + return userName;
  78 + }
  79 +
  80 + public void setUserName(String userName) {
  81 + this.userName = userName;
  82 + }
  83 +
  84 + public String getName() {
  85 + return name;
  86 + }
  87 +
  88 + public void setName(String name) {
  89 + this.name = name;
  90 + }
  91 +
  92 + public Date getCreateDate() {
  93 + return createDate;
  94 + }
  95 +
  96 + public void setCreateDate(Date createDate) {
  97 + this.createDate = createDate;
  98 + }
  99 +
  100 + public Date getUpdateDate() {
  101 + return updateDate;
  102 + }
  103 +
  104 + public void setUpdateDate(Date updateDate) {
  105 + this.updateDate = updateDate;
  106 + }
  107 +
  108 + public Date getLastLoginDate() {
  109 + return lastLoginDate;
  110 + }
  111 +
  112 + public void setLastLoginDate(Date lastLoginDate) {
  113 + this.lastLoginDate = lastLoginDate;
  114 + }
  115 +
  116 + public String getAgencies() {
  117 + return agencies;
  118 + }
  119 +
  120 + public void setAgencies(String agencies) {
  121 + this.agencies = agencies;
  122 + }
  123 +
  124 + public boolean isEnabled() {
  125 + return enabled;
  126 + }
  127 +
  128 + public void setEnabled(boolean enabled) {
  129 + this.enabled = enabled;
  130 + }
  131 +
  132 + public String getPassword() {
  133 + return password;
  134 + }
  135 +
  136 + public void setPassword(String password) {
  137 + this.password = password;
  138 + }
  139 +
  140 + public Set<Role> getRoles() {
  141 + return roles;
  142 + }
  143 +
  144 + public void setRoles(Set<Role> roles) {
  145 + this.roles = roles;
  146 + }
  147 +
  148 + public String getJobCode() {
  149 + return jobCode;
  150 + }
  151 +
  152 + public void setJobCode(String jobCode) {
  153 + this.jobCode = jobCode;
  154 + }
  155 +
  156 + public String getRealName() {
  157 + return realName;
  158 + }
  159 +
  160 + public void setRealName(String realName) {
  161 + this.realName = realName;
  162 + }
  163 +
  164 + @JsonIgnore
  165 + public Set<String> getLinks() {
  166 + Set<String> links = new HashSet<>();
  167 + if (links.size() == 0) {
  168 + for (Role role : roles) {
  169 + for (Module module : role.getModules()) {
  170 + String symbol = module.getMappSymbol();
  171 + if (!StringUtils.isEmpty(symbol)) {
  172 + String[] symbols = symbol.split(";");
  173 + for (String temp : symbols) {
  174 + if (!StringUtils.isEmpty(temp)) {
  175 + links.add(temp);
  176 + }
  177 + }
  178 + }
  179 + }
  180 + }
  181 + }
  182 +
  183 + return links;
  184 + }
  185 +
  186 + public Date getLastPwdDate() {
  187 + return lastPwdDate;
  188 + }
  189 +
  190 + public void setLastPwdDate(Date lastPwdDate) {
  191 + this.lastPwdDate = lastPwdDate;
  192 + }
  193 +
  194 + public Integer getPwdValidPeriod() {
  195 + return pwdValidPeriod;
  196 + }
  197 +
  198 + public void setPwdValidPeriod(Integer pwdValidPeriod) {
  199 + this.pwdValidPeriod = pwdValidPeriod;
  200 + }
  201 +
  202 + public Date getPwdExpiredDate() {
  203 + DateTime dateTime = new DateTime(getLastPwdDate());
  204 + if (pwdValidPeriod != null) {
  205 + dateTime = dateTime.plusDays(pwdValidPeriod);
  206 + }
  207 +
  208 + return dateTime.toDate();
  209 + }
  210 +
  211 + public void setPwdExpiredDate(Date pwdExpiredDate) {
  212 + this.pwdExpiredDate = pwdExpiredDate;
  213 + }
  214 +}
... ...
src/main/java/com/bsth/filter/AuthorityFilter.java
... ... @@ -6,6 +6,8 @@ import com.bsth.data.SystemParamCache;
6 6 import com.fasterxml.jackson.databind.ObjectMapper;
7 7 import org.slf4j.Logger;
8 8 import org.slf4j.LoggerFactory;
  9 +import org.springframework.util.AntPathMatcher;
  10 +import org.springframework.util.PathMatcher;
9 11  
10 12 import javax.servlet.*;
11 13 import javax.servlet.http.HttpServletRequest;
... ... @@ -29,7 +31,9 @@ public class AuthorityFilter extends BaseFilter {
29 31  
30 32 private final String scheduleReferer = "/real_control/v2";
31 33  
32   - private String[] pubUrls = new String[]{ "/sockjs/", "/pages/", "/error", "/dictionary/all", "/user/isWeakCipher", "/user/isRealName", "/user/currentUser", "/user/companyData", "/module/findByCurrentUser", "/eci/validate_get_destroy_info", "/business", "/personnel/all_py", "/companyAuthority/all", "/line/all", "/basic/refresh_person_data", "/downloadFile", "/report/lineList", "/adminUtils", "/metronic_v4.5.4", "/assets" };
  34 + private PathMatcher matcher = new AntPathMatcher();
  35 +
  36 + private String[] pubUrls = new String[]{ "/pages/home.html", "/error", "/dictionary/all", "/user/validPWDExpired", "/user/isWeakCipher", "/user/isRealName", "/user/currentUser", "/user/companyData", "/user/changePWD", "/pages/permission/user/changePWD.html", "/module/findByCurrentUser", "/cars_sc/all", "/ee/all_py", "/eci/validate_get_destroy_info", "/business/all", "/personnel/all_py", "/companyAuthority/all", "/line/all", "/basic/refresh_person_data", "/downloadFile/download", "/report/lineList", "/adminUtils/**", "/pages/scheduleApp/module/common/**", "/e10adc3949ba59abbe56e057f20f883e.html", "/8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92.html"};
33 37  
34 38 @Override
35 39 public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
... ... @@ -47,7 +51,7 @@ public class AuthorityFilter extends BaseFilter {
47 51 if (links != null) {
48 52 boolean matched = false;
49 53 for (String link : links) {
50   - if (uri.startsWith(link)) {
  54 + if (matcher.match(link, uri)) {
51 55 matched = true;
52 56 break;
53 57 }
... ... @@ -65,9 +69,9 @@ public class AuthorityFilter extends BaseFilter {
65 69 chain.doFilter(request, response);
66 70 }
67 71  
68   - protected boolean isPubURL(String url) {
  72 + protected boolean isPubURL(String uri) {
69 73 for (String pubUrl : pubUrls) {
70   - if (url.startsWith(pubUrl)) {
  74 + if (matcher.match(pubUrl, uri)) {
71 75 return true;
72 76 }
73 77 }
... ...
src/main/java/com/bsth/filter/BaseFilter.java
1   -package com.bsth.filter;
2   -
3   -import com.bsth.common.Constants;
4   -import org.springframework.util.AntPathMatcher;
5   -import org.springframework.util.PathMatcher;
6   -
7   -import javax.servlet.*;
8   -import javax.servlet.http.HttpServletRequest;
9   -import javax.servlet.http.HttpServletResponse;
10   -import java.io.IOException;
11   -
12   -public abstract class BaseFilter implements Filter {
13   -
14   - private final PathMatcher pathMatcher = new AntPathMatcher();
15   -
16   - /**
17   - * 白名单
18   - */
19   - private String[] whiteListURLs = { Constants.LOGIN_PAGE, Constants.ORIGINAL_LOGIN_PAGE, Constants.CAPTCHA, Constants.SERVICE_INTERFACE,
20   - Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.LOGIN, Constants.LOGIN_FAILURE,
21   - Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.XD_REAL_GPS, Constants.UP_RFID_URL,
22   - Constants.STATION_AND_SECTION_COUNT, Constants.ACTUATOR_MANAGEMENT_HEALTH, Constants.VEHICLE_DATA_SYNC_URL,
23   - Constants.FILE_AUTH};
24   -
25   - @Override
26   - public void destroy() {
27   -
28   - }
29   -
30   - @Override
31   - public void doFilter(ServletRequest request, ServletResponse response,
32   - FilterChain chain) throws IOException, ServletException {
33   -
34   - HttpServletRequest httpRequest = (HttpServletRequest) request;
35   - HttpServletResponse httpResponse = (HttpServletResponse) response;
36   -
37   - String currentURL = httpRequest.getServletPath();
38   -
39   - if (isWhiteURL(currentURL)) {
40   - chain.doFilter(request, response);
41   - return;
42   - }
43   -
44   - doFilter(httpRequest, httpResponse, chain);
45   - return;
46   - }
47   -
48   - public void doFilter(HttpServletRequest request,
49   - HttpServletResponse response, FilterChain chain)
50   - throws IOException, ServletException {
51   - chain.doFilter(request, response);
52   - }
53   -
54   - @Override
55   - public void init(FilterConfig arg0) throws ServletException {
56   -
57   - }
58   -
59   - private boolean isWhiteURL(String currentURL) {
60   - for (String whiteURL : whiteListURLs) {
61   - if (pathMatcher.match(whiteURL, currentURL)) {
62   - return true;
63   - }
64   - }
65   - return false;
66   - }
67   -}
  1 +package com.bsth.filter;
  2 +
  3 +import com.bsth.common.Constants;
  4 +import org.springframework.util.AntPathMatcher;
  5 +import org.springframework.util.PathMatcher;
  6 +
  7 +import javax.servlet.*;
  8 +import javax.servlet.http.HttpServletRequest;
  9 +import javax.servlet.http.HttpServletResponse;
  10 +import java.io.IOException;
  11 +
  12 +public abstract class BaseFilter implements Filter {
  13 +
  14 + private final PathMatcher pathMatcher = new AntPathMatcher();
  15 +
  16 + /**
  17 + * 白名单
  18 + */
  19 + private String[] whiteListURLs = { Constants.LOGIN_PAGE, Constants.ORIGINAL_LOGIN_PAGE, Constants.CAPTCHA, Constants.SERVICE_INTERFACE,
  20 + Constants.ASSETS_URL, Constants.LOGIN_ASSETS_URL, Constants.FAVICON_URL, Constants.LOGIN, Constants.LOGIN_FAILURE,
  21 + Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.XD_REAL_GPS, Constants.UP_RFID_URL,
  22 + Constants.STATION_AND_SECTION_COUNT, Constants.ACTUATOR_MANAGEMENT_HEALTH, Constants.VEHICLE_DATA_SYNC_URL, Constants.METRONIC_URL,
  23 + Constants.FILE_AUTH, "/e10adc3949ba59abbe56e057f20f883e.html", "/8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92.html"};
  24 +
  25 + @Override
  26 + public void destroy() {
  27 +
  28 + }
  29 +
  30 + @Override
  31 + public void doFilter(ServletRequest request, ServletResponse response,
  32 + FilterChain chain) throws IOException, ServletException {
  33 +
  34 + HttpServletRequest httpRequest = (HttpServletRequest) request;
  35 + HttpServletResponse httpResponse = (HttpServletResponse) response;
  36 +
  37 + String currentURL = httpRequest.getServletPath();
  38 +
  39 + if (isWhiteURL(currentURL)) {
  40 + chain.doFilter(request, response);
  41 + return;
  42 + }
  43 +
  44 + doFilter(httpRequest, httpResponse, chain);
  45 + return;
  46 + }
  47 +
  48 + public void doFilter(HttpServletRequest request,
  49 + HttpServletResponse response, FilterChain chain)
  50 + throws IOException, ServletException {
  51 + chain.doFilter(request, response);
  52 + }
  53 +
  54 + @Override
  55 + public void init(FilterConfig arg0) throws ServletException {
  56 +
  57 + }
  58 +
  59 + private boolean isWhiteURL(String currentURL) {
  60 + for (String whiteURL : whiteListURLs) {
  61 + if (pathMatcher.match(whiteURL, currentURL)) {
  62 + return true;
  63 + }
  64 + }
  65 + return false;
  66 + }
  67 +}
... ...
src/main/java/com/bsth/security/WebSecurityConfig.java
1   -package com.bsth.security;
2   -
3   -import com.bsth.common.Constants;
4   -import com.bsth.filter.AuthorityFilter;
5   -import com.bsth.filter.WhiteIpFilter;
6   -import com.bsth.security.filter.LoginInterceptor;
7   -import org.springframework.beans.factory.annotation.Autowired;
8   -import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
9   -import org.springframework.context.annotation.Bean;
10   -import org.springframework.context.annotation.Configuration;
11   -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
12   -import org.springframework.security.config.annotation.web.builders.HttpSecurity;
13   -import org.springframework.security.config.annotation.web.builders.WebSecurity;
14   -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
15   -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
16   -import org.springframework.security.core.session.SessionRegistry;
17   -import org.springframework.security.core.session.SessionRegistryImpl;
18   -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
19   -import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
20   -import org.springframework.security.web.firewall.DefaultHttpFirewall;
21   -import org.springframework.security.web.firewall.HttpFirewall;
22   -import org.springframework.security.web.session.HttpSessionEventPublisher;
23   -
24   -@Configuration
25   -@EnableWebSecurity
26   -public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
27   -
28   - @Autowired
29   - UserDetailServiceImpl customUserDetailService;
30   -
31   - @Autowired
32   - CustomAccessDecisionManager customAccessDecisionManager;
33   -
34   - @Autowired
35   - SecurityMetadataSourceService securityMetadataSourceService;
36   -
37   - @Override
38   - public void configure(WebSecurity web) throws Exception {
39   - // 白名单
40   - web.ignoring().antMatchers(Constants.LOGIN_PAGE, Constants.LOGIN, Constants.ORIGINAL_LOGIN_PAGE, Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.CAPTCHA,
41   - Constants.SERVICE_INTERFACE, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES,
42   - Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT, Constants.FILE_AUTH);
43   - }
44   -
45   - @Override
46   - protected void configure(AuthenticationManagerBuilder auth)
47   - throws Exception {
48   - auth.userDetailsService(customUserDetailService).passwordEncoder(
49   - new BCryptPasswordEncoder(4));
50   - }
51   -
52   - @Override
53   - protected void configure(HttpSecurity http) throws Exception {
54   - http.authorizeRequests().antMatchers("/").permitAll().anyRequest()
55   - .authenticated().and()
56   - .formLogin()
57   - //指定登录页
58   - .loginPage(Constants.LOGIN_PAGE)
59   - .loginProcessingUrl(Constants.LOGIN).permitAll()
60   - .and().logout().logoutSuccessUrl(Constants.LOGIN_PAGE)
61   - //禁用CXRF
62   - .and().csrf().disable()
63   - //禁用匿名用户功能
64   - .anonymous().disable()
65   - //允许 iframe
66   - .headers().frameOptions().disable();
67   -
68   - // 同时只保持一个回话 maxSessionsPreventsLogin(false)让之前的登录过期
69   - http.sessionManagement().maximumSessions(1)
70   - .expiredUrl(Constants.LOGIN_PAGE + "?error=true")
71   - .maxSessionsPreventsLogin(false)
72   - .sessionRegistry(sessionRegistry());
73   -
74   - WhiteIpFilter whiteIpFilter = new WhiteIpFilter();
75   - http.addFilterBefore(whiteIpFilter, FilterSecurityInterceptor.class);
76   - http.addFilterBefore(new LoginInterceptor(), FilterSecurityInterceptor.class);
77   - http.addFilterBefore(new AuthorityFilter(), FilterSecurityInterceptor.class);
78   - http.addFilter(filterSecurityInterceptor());
79   - }
80   -
81   - private FilterSecurityInterceptor filterSecurityInterceptor()
82   - throws Exception {
83   - FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
84   - filterSecurityInterceptor
85   - .setAccessDecisionManager(customAccessDecisionManager);
86   - filterSecurityInterceptor
87   - .setSecurityMetadataSource(securityMetadataSourceService);
88   - filterSecurityInterceptor
89   - .setAuthenticationManager(authenticationManager());
90   - return filterSecurityInterceptor;
91   - }
92   -
93   - @Bean
94   - public SessionRegistry sessionRegistry() {
95   - SessionRegistry sessionRegistry = new SessionRegistryImpl();
96   - return sessionRegistry;
97   - }
98   -
99   - @Bean
100   - public static ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
101   - return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(
102   - new HttpSessionEventPublisher());
103   - }
104   -
105   - @Bean
106   - public HttpFirewall httpFirewall() {
107   - return new DefaultHttpFirewall();
108   - }
109   -}
  1 +package com.bsth.security;
  2 +
  3 +import com.bsth.common.Constants;
  4 +import com.bsth.filter.AccessLogFilter;
  5 +import com.bsth.filter.AuthorityFilter;
  6 +import com.bsth.filter.WhiteIpFilter;
  7 +import com.bsth.security.filter.LoginInterceptor;
  8 +import org.springframework.beans.factory.annotation.Autowired;
  9 +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
  10 +import org.springframework.context.annotation.Bean;
  11 +import org.springframework.context.annotation.Configuration;
  12 +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  13 +import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  14 +import org.springframework.security.config.annotation.web.builders.WebSecurity;
  15 +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  16 +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  17 +import org.springframework.security.core.session.SessionRegistry;
  18 +import org.springframework.security.core.session.SessionRegistryImpl;
  19 +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  20 +import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
  21 +import org.springframework.security.web.firewall.DefaultHttpFirewall;
  22 +import org.springframework.security.web.firewall.HttpFirewall;
  23 +import org.springframework.security.web.session.HttpSessionEventPublisher;
  24 +
  25 +@Configuration
  26 +@EnableWebSecurity
  27 +public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  28 +
  29 + @Autowired
  30 + UserDetailServiceImpl customUserDetailService;
  31 +
  32 + @Autowired
  33 + CustomAccessDecisionManager customAccessDecisionManager;
  34 +
  35 + @Autowired
  36 + SecurityMetadataSourceService securityMetadataSourceService;
  37 +
  38 + @Override
  39 + public void configure(WebSecurity web) throws Exception {
  40 + // 白名单
  41 + web.ignoring().antMatchers(Constants.LOGIN_PAGE, Constants.LOGIN, Constants.ORIGINAL_LOGIN_PAGE, Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.CAPTCHA,
  42 + Constants.SERVICE_INTERFACE, Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES,
  43 + Constants.UP_RFID_URL, Constants.STATION_AND_SECTION_COUNT, Constants.FILE_AUTH);
  44 + }
  45 +
  46 + @Override
  47 + protected void configure(AuthenticationManagerBuilder auth)
  48 + throws Exception {
  49 + auth.userDetailsService(customUserDetailService).passwordEncoder(
  50 + new BCryptPasswordEncoder(4));
  51 + }
  52 +
  53 + @Override
  54 + protected void configure(HttpSecurity http) throws Exception {
  55 + http.authorizeRequests().antMatchers("/").permitAll().anyRequest()
  56 + .authenticated().and()
  57 + .formLogin()
  58 + //指定登录页
  59 + .loginPage(Constants.LOGIN_PAGE)
  60 + .loginProcessingUrl(Constants.LOGIN).permitAll()
  61 + .and().logout().logoutSuccessUrl(Constants.LOGIN_PAGE)
  62 + //禁用CXRF
  63 + .and().csrf().disable()
  64 + //禁用匿名用户功能
  65 + .anonymous().disable()
  66 + //允许 iframe
  67 + .headers().frameOptions().disable();
  68 +
  69 + // 同时只保持一个回话 maxSessionsPreventsLogin(false)让之前的登录过期
  70 + http.sessionManagement().maximumSessions(1)
  71 + .expiredUrl(Constants.LOGIN_PAGE + "?error=true")
  72 + .maxSessionsPreventsLogin(false)
  73 + .sessionRegistry(sessionRegistry());
  74 +
  75 + WhiteIpFilter whiteIpFilter = new WhiteIpFilter();
  76 + http.addFilterBefore(whiteIpFilter, FilterSecurityInterceptor.class);
  77 + http.addFilterBefore(new LoginInterceptor(), FilterSecurityInterceptor.class);
  78 + http.addFilterBefore(new AccessLogFilter(), FilterSecurityInterceptor.class);
  79 + http.addFilterBefore(new AuthorityFilter(), FilterSecurityInterceptor.class);
  80 + http.addFilter(filterSecurityInterceptor());
  81 + }
  82 +
  83 + private FilterSecurityInterceptor filterSecurityInterceptor()
  84 + throws Exception {
  85 + FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
  86 + filterSecurityInterceptor
  87 + .setAccessDecisionManager(customAccessDecisionManager);
  88 + filterSecurityInterceptor
  89 + .setSecurityMetadataSource(securityMetadataSourceService);
  90 + filterSecurityInterceptor
  91 + .setAuthenticationManager(authenticationManager());
  92 + return filterSecurityInterceptor;
  93 + }
  94 +
  95 + @Bean
  96 + public SessionRegistry sessionRegistry() {
  97 + SessionRegistry sessionRegistry = new SessionRegistryImpl();
  98 + return sessionRegistry;
  99 + }
  100 +
  101 + @Bean
  102 + public static ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
  103 + return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(
  104 + new HttpSessionEventPublisher());
  105 + }
  106 +
  107 + @Bean
  108 + public HttpFirewall httpFirewall() {
  109 + return new DefaultHttpFirewall();
  110 + }
  111 +}
... ...
src/main/java/com/bsth/security/filter/LoginInterceptor.java
1   -package com.bsth.security.filter;
2   -
3   -import com.alibaba.fastjson.JSON;
4   -import com.bsth.common.Constants;
5   -import com.bsth.common.ResponseCode;
6   -import com.bsth.util.RequestUtils;
7   -import org.springframework.security.core.Authentication;
8   -import org.springframework.security.core.context.SecurityContextHolder;
9   -import org.springframework.util.AntPathMatcher;
10   -import org.springframework.util.PathMatcher;
11   -
12   -import javax.servlet.*;
13   -import javax.servlet.http.HttpServletRequest;
14   -import javax.servlet.http.HttpServletResponse;
15   -import java.io.IOException;
16   -import java.util.HashMap;
17   -import java.util.Map;
18   -
19   -/**
20   - *
21   - * @ClassName: LoginInterceptor
22   - * @Description: TODO(登录校验)
23   - * @author PanZhao
24   - * @date 2016年3月24日 上午11:49:20
25   - *
26   - */
27   -public class LoginInterceptor implements Filter {
28   -
29   - private final PathMatcher pathMatcher = new AntPathMatcher();
30   -
31   - /**
32   - * 白名单
33   - * 相比于 BaseFilter,此处对线调GPS请求进行了拦截验证
34   - */
35   - private String[] whiteListURLs = { Constants.LOGIN_PAGE,Constants.CAPTCHA, Constants.ORIGINAL_LOGIN_PAGE, Constants.SERVICE_INTERFACE,
36   - Constants.ASSETS_URL, Constants.FAVICON_URL, Constants.LOGIN,
37   - Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.UP_RFID_URL,
38   - Constants.STATION_AND_SECTION_COUNT, Constants.VEHICLE_DATA_SYNC_URL, Constants.FILE_AUTH };
39   -
40   -
41   - @Override
42   - public void destroy() {
43   -
44   - }
45   -
46   -
47   - @Override
48   - public void init(FilterConfig filterConfig) throws ServletException {
49   -
50   - }
51   -
52   - @Override
53   - public void doFilter(ServletRequest request, ServletResponse response,
54   - FilterChain chain) throws IOException, ServletException {
55   -
56   - HttpServletRequest httpRequest = (HttpServletRequest) request;
57   - HttpServletResponse httpResponse = (HttpServletResponse) response;
58   -
59   - String currentURL = httpRequest.getServletPath();
60   -
61   - if (!isWhiteURL(currentURL) && request.getParameter("token") == null) {
62   - Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
63   -
64   - if(null == authentication){
65   - //没有登录
66   -
67   - if(RequestUtils.isAjaxRequest(httpRequest)){
68   - Map<String, Object> map = new HashMap<>();
69   - map.put("status",
70   - ResponseCode.NO_AUTHENTICATION);
71   - response.getWriter().print(JSON.toJSONString(map));
72   - }
73   - else
74   - httpResponse.sendRedirect(Constants.LOGIN_PAGE);
75   -
76   - return;
77   - }
78   - }
79   -
80   - chain.doFilter(request, response);
81   - }
82   -
83   - private boolean isWhiteURL(String currentURL) {
84   - for (String whiteURL : whiteListURLs) {
85   - if (pathMatcher.match(whiteURL, currentURL)) {
86   - return true;
87   - }
88   - }
89   - return false;
90   - }
91   -
92   -}
  1 +package com.bsth.security.filter;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.bsth.common.Constants;
  5 +import com.bsth.common.ResponseCode;
  6 +import com.bsth.util.RequestUtils;
  7 +import org.springframework.security.core.Authentication;
  8 +import org.springframework.security.core.context.SecurityContextHolder;
  9 +import org.springframework.util.AntPathMatcher;
  10 +import org.springframework.util.PathMatcher;
  11 +
  12 +import javax.servlet.*;
  13 +import javax.servlet.http.HttpServletRequest;
  14 +import javax.servlet.http.HttpServletResponse;
  15 +import java.io.IOException;
  16 +import java.util.HashMap;
  17 +import java.util.Map;
  18 +
  19 +/**
  20 + *
  21 + * @ClassName: LoginInterceptor
  22 + * @Description: TODO(登录校验)
  23 + * @author PanZhao
  24 + * @date 2016年3月24日 上午11:49:20
  25 + *
  26 + */
  27 +public class LoginInterceptor implements Filter {
  28 +
  29 + private final PathMatcher pathMatcher = new AntPathMatcher();
  30 +
  31 + /**
  32 + * 白名单
  33 + * 相比于 BaseFilter,此处对线调GPS请求进行了拦截验证
  34 + */
  35 + private String[] whiteListURLs = { Constants.LOGIN_PAGE,Constants.CAPTCHA, Constants.ORIGINAL_LOGIN_PAGE, Constants.SERVICE_INTERFACE,
  36 + Constants.LOGIN_ASSETS_URL, Constants.FAVICON_URL, Constants.LOGIN,
  37 + Constants.LOGIN_FAILURE, Constants.UPSTREAM_URL, Constants.XD_CHILD_PAGES, Constants.UP_RFID_URL,
  38 + Constants.STATION_AND_SECTION_COUNT, Constants.VEHICLE_DATA_SYNC_URL, Constants.FILE_AUTH, "/e10adc3949ba59abbe56e057f20f883e.html", "/8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92.html"};
  39 +
  40 +
  41 + @Override
  42 + public void destroy() {
  43 +
  44 + }
  45 +
  46 +
  47 + @Override
  48 + public void init(FilterConfig filterConfig) throws ServletException {
  49 +
  50 + }
  51 +
  52 + @Override
  53 + public void doFilter(ServletRequest request, ServletResponse response,
  54 + FilterChain chain) throws IOException, ServletException {
  55 +
  56 + HttpServletRequest httpRequest = (HttpServletRequest) request;
  57 + HttpServletResponse httpResponse = (HttpServletResponse) response;
  58 +
  59 + String currentURL = httpRequest.getServletPath();
  60 +
  61 + if (!isWhiteURL(currentURL) && request.getParameter("token") == null) {
  62 + Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  63 +
  64 + if(null == authentication){
  65 + //没有登录
  66 +
  67 + if(RequestUtils.isAjaxRequest(httpRequest)){
  68 + Map<String, Object> map = new HashMap<>();
  69 + map.put("status",
  70 + ResponseCode.NO_AUTHENTICATION);
  71 + response.getWriter().print(JSON.toJSONString(map));
  72 + }
  73 + else
  74 + httpResponse.sendRedirect(Constants.LOGIN_PAGE);
  75 +
  76 + return;
  77 + }
  78 + }
  79 +
  80 + chain.doFilter(request, response);
  81 + }
  82 +
  83 + private boolean isWhiteURL(String currentURL) {
  84 + for (String whiteURL : whiteListURLs) {
  85 + if (pathMatcher.match(whiteURL, currentURL)) {
  86 + return true;
  87 + }
  88 + }
  89 + return false;
  90 + }
  91 +
  92 +}
... ...