本文總結自實習中對項目對重構。原先項目採用Springboot+freemarker模版,開發過程當中以爲前端邏輯寫的實在噁心,後端Controller層還必須返回Freemarker模版的ModelAndView,逐漸有了先後端分離的想法,因爲以前比沒有接觸過,主要參考的仍是網上的一些博客教程等,初步完成了先後端分離,在此記錄必備查閱。css
1、先後端分離思想 前端從後端剝離,造成一個前端工程,前端只利用Json來和後端進行交互,後端不返回頁面,只返回Json數據。先後端之間徹底經過public API約定。 2、後端 Springboot Springboot就再也不贅述了,Controller層返回Json數據。
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public JSONResult addClient(@RequestBody String param) {
JSONObject jsonObject = JSON.parseObject(param);
String task = jsonObject.getString("task");
List<Object> list = jsonObject.getJSONArray("attributes");
List<String> attrList = new LinkedList(list);
Client client = JSON.parseObject(jsonObject.getJSONObject("client").toJSONString(),new TypeReference<Client>(){});
clientService.addClient(client, task, attrList);
return JSONResult.ok();
}
Post請求使用@RequestBody參數接收。前端
3、前端 Vue + ElementUI + Vue router + Vuex + axios + webpack 主要參考:
1.Vue官網node
2.一個基於Vue+ElementUI實現的前端工程教程,很贊,前端工程照着這個例子搭建起來後,能夠參考它的升級版webpack
這裏主要說一下開發工程中遇到的問題:ios
因爲開發中前端工程使用webpack啓了一個服務,因此先後端並不在一個端口下,必然涉及到跨域:nginx
XMLHttpRequest會遵照同源策略(same-origin policy). 也即腳本只能訪問相同協議/相同主機名/相同端口的資源, 若是要突破這個限制, 那就是所謂的跨域, 此時須要遵照CORS(Cross-Origin Resource Sharing)機制。web
解決跨域分兩種:算法
1.server端是本身開發的,這樣能夠在在後端增長一個攔截器npm
@Component
public class CommonIntercepter implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//容許跨域,不能放在postHandle內
response.setHeader("Access-Control-Allow-Origin", "*");
if (request.getMethod().equals("OPTIONS")) {
response.addHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH");
response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
}
return true;
}
}
response.setHeader("Access-Control-Allow-Origin", "*");
主要就是在Response Header中增長 "Access-Control-Allow-Origin: *"json
if (request.getMethod().equals("OPTIONS")) {
response.addHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH");
response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
}
因爲咱們在先後端分離中集成了shiro,所以須要在headers中自定義一個'Authorization'字段,此時普通的GET、POST等請求會變成preflighted request,即在GET、POST請求以前會預先發一個OPTIONS請求,這個後面再說。推薦一篇博客介紹 preflighted request。
2.server端不是本身開發的,能夠在前端加proxyTable,參考這個,不過這個只能在開發的時候用,後續部署,能夠把前端項目做爲靜態資源放到後端,這樣就不存在跨域(因爲項目須要,我如今是這麼作的,根據網上博客介紹,可使用nginx,具體怎麼作能夠在網上搜一下)。
遇到了網上不少人說的,proxyTable不管如何修改,都沒效果的現象。
1.(很是重要)確保proxyTable配置的地址能訪問,由於若是不能訪問,在瀏覽器F12調試的時候看到的依然會是提示404。
而且注意,在F12看到的js提示錯誤的域名,是js寫的那個域名,並非代理後的域名。(l樓主就遇到這個問題,後端地址缺乏了查詢參數,代理設置爲後端地址,然而F12看到的錯誤依然仍是本地的域名,並非代理後的域名)
2.就是要手動再執行一次npm run dev
4、先後端分離項目中集成shiro 能夠參考:在先後端分離的Springboot項目中集成Shiro權限框架
這裏說一下實際開發集成過程當中遇到的問題:
先後端分離項目中,因爲跨域,會致使複雜請求,即會發送preflighted request,這樣會致使在GET/POST等請求以前會先發一個OPTIONS請求,但OPTIONS請求並不帶shiro的'Authorization'字段(shiro的Session),即OPTIONS請求不能經過shiro驗證,會返回未認證的信息。
解決方法:給shiro增長一個過濾器,過濾OPTIONS請求
public class CORSAuthenticationFilter extends FormAuthenticationFilter {
private static final Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class);
public CORSAuthenticationFilter() {
super();
}
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
return true;
}
}
return super.isAccessAllowed(request, response, mappedValue);
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse res = (HttpServletResponse)response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setStatus(HttpServletResponse.SC_OK);
res.setCharacterEncoding("UTF-8");
PrintWriter writer = res.getWriter();
Map<String, Object> map= new HashMap<>();
map.put("code", 702);
map.put("msg", "未登陸");
writer.write(JSON.toJSONString(map));
writer.close();
return false;
}
}
貼一下個人config文件:
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
return new DDRealm();
}
@Bean
public CacheManager cacheManager() {
return new MemoryConstrainedCacheManager();
}
/**
* cookie對象;
* rememberMeCookie()方法是設置Cookie的生成模版,好比cookie的name,cookie的有效時間等等。
* @return
*/
@Bean
public SimpleCookie rememberMeCookie(){
//System.out.println("ShiroConfiguration.rememberMeCookie()");
//這個參數是cookie的名稱,對應前端的checkbox的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
//<!-- 記住我cookie生效時間30天 ,單位秒;-->
simpleCookie.setMaxAge(259200);
return simpleCookie;
}
/**
* cookie管理對象;
* rememberMeManager()方法是生成rememberMe管理器,並且要將這個rememberMe管理器設置到securityManager中
* @return
*/
@Bean
public CookieRememberMeManager rememberMeManager(){
//System.out.println("ShiroConfiguration.rememberMeManager()");
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
//rememberMe cookie加密的密鑰 建議每一個項目都不同 默認AES算法 密鑰長度(128 256 512 位)
cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
return cookieRememberMeManager;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager sm = new DefaultWebSecurityManager();
sm.setRealm(realm());
sm.setCacheManager(cacheManager());
//注入記住我管理器
sm.setRememberMeManager(rememberMeManager());
//注入自定義sessionManager
sm.setSessionManager(sessionManager());
return sm;
}
//自定義sessionManager
@Bean
public SessionManager sessionManager() {
return new CustomSessionManager();
}
public CORSAuthenticationFilter corsAuthenticationFilter(){
return new CORSAuthenticationFilter();
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
//SecurityUtils.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//配置不會被攔截的連接,順序判斷
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/static/js/**", "anon");
filterChainDefinitionMap.put("/static/css/**", "anon");
filterChainDefinitionMap.put("/static/fonts/**", "anon");
filterChainDefinitionMap.put("/login/**", "anon");
filterChainDefinitionMap.put("/corp/call_back/receive", "anon");
//authc:全部url必須經過認證才能訪問,anon:全部url均可以匿名訪問
filterChainDefinitionMap.put("/**", "corsAuthenticationFilter");
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
//自定義過濾器
Map<String, Filter> filterMap = new LinkedHashMap<>();
filterMap.put("corsAuthenticationFilter", corsAuthenticationFilter());
shiroFilter.setFilters(filterMap);
return shiroFilter;
}
/**
* Shiro生命週期處理器 * @return
*/
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 開啓Shiro的註解(如@RequiresRoles,@RequiresPermissions),需藉助SpringAOP掃描使用Shiro註解的類,並在必要時進行安全邏輯驗證 * 配置如下兩個bean(DefaultAdvisorAutoProxyCreator(可選)和AuthorizationAttributeSourceAdvisor)便可實現此功能 * @return
*/
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
shiro session默認失效時間是30min,咱們在自定義的sessionManager的構造函數中設置失效時間爲其餘值
public class CustomSessionManager extends DefaultWebSessionManager {
private static final Logger logger = LoggerFactory.getLogger(CustomSessionManager.class);
private static final String AUTHORIZATION = "Authorization";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public CustomSessionManager() {
super();
setGlobalSessionTimeout(DEFAULT_GLOBAL_SESSION_TIMEOUT * 48);
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);//若是請求頭中有 Authorization 則其值爲sessionId
if (!StringUtils.isEmpty(sessionId)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return sessionId;
} else {
//不然按默認規則從cookie取sessionId
return super.getSessionId(request, response);
}
}
}
5、部署項目 前端項目部署主要分兩種方法:
1.將前端項目打包(npm run build)成靜態資源文件,放入後端,一塊兒打包。後端寫一個Controller返回前端界面(我使用Vue開發的是單頁面應用),可是這樣其實又將先後端耦合在一塊兒了,不過起碼作到先後端分離開發,方便開發的目的已經達成,也初步達成了要求,因爲項目的須要,我是這樣作的,而且免去了跨域問題。
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String index() {
return "/index";
}
2.將前端工程另啓一個服務(tomcat,nginx,nodejs),這樣有跨域的問題。
說一下我遇到的問題:
不使用shiro的 shiroFilter.setLoginUrl("/unauth");
當頁面無權限訪問時,咱們在過濾器裏直接返回錯誤信息,不利用shiro自帶的跳轉。看過濾器中的onAccessDenied函數
public class CORSAuthenticationFilter extends FormAuthenticationFilter { private static final Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class); public CORSAuthenticationFilter() { super(); } @Override public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { //Always return true if the request's method is OPTIONS if (request instanceof HttpServletRequest) { if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) { return true; } } return super.isAccessAllowed(request, response, mappedValue); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletResponse res = (HttpServletResponse)response; res.setHeader("Access-Control-Allow-Origin", "*"); res.setStatus(HttpServletResponse.SC_OK); res.setCharacterEncoding("UTF-8"); PrintWriter writer = res.getWriter(); Map<String, Object> map= new HashMap<>(); map.put("code", 702); map.put("msg", "未登陸"); writer.write(JSON.toJSONString(map)); writer.close(); return false; }}