由於項目要加上公司的sso,出現的一系列問題,找到解決辦法,在此記錄一下。可能並不適合其他項目,給個參考。
前提:
前端是vue.js,后端springboot
sso配置需要增加公司自己的maven依賴和yml配置。
啟動項目后,首先訪問后端/index接口,進入sso攔截,訪問sso頁面;登陸成功后返回goto指向的url(也就是index接口的return內容),附上/index接口代碼:
@GetMapping(value={"/dist","dist/index"}) public String index(HttpServletRequest request) { User user = UserUtils.getCurrentUser(request); request.getSession().setAttribute("user", user); return "redirect:http://192.168.0.XXX:8081"; //開發環境 // return "redirect:/loginShow"; //正式環境 } @RequestMapping("/loginShow") public ModelAndView loginShow(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("redirect:/dist/index.html"); return modelAndView; }
(其中loginShow方法是用來解決url顯示token參數問題的,加上之后sso跳轉url的參數隱藏)。
這時,前端訪問接口報錯,跨域問題。
如果是vue2.0,可以在axios的封裝類之中加上一句話:
axios.defaults.withCredentials = true;
加在axios.create(...)之前,這句話的作用是訪問接口時帶着參數,比如token、session。
如果是vue3.0,還需要在vue.config.js中的module.exports里面增加proxy代理,如果沒有vue.config.js,可以創建一個。代理代碼如下:
devServer: { proxy: { '/api': { target: 'http://192.168.0.XXX:8080/XXXXXX', changeOrigin: true, pathRewrite: { '^/api': '' } } } }
然后,請求基礎路徑需要都改成和上面的路徑一致,比如這里寫的'/api',那么項目中baseUrl的dev或pro路徑也要寫成'/api'(可以自定義,不用非叫'api',只要一致就好)。