首先,說明運行環境,前后端分離,跨域。
先說一下跨域,跨域最好不要直接用注解形式,很麻煩,因為如果有需要設置的內容時還要一個一個找到注解更改,直接配置bean方便很多
1 @Bean 2 private CorsConfiguration buildConfig() { 3 CorsConfiguration corsConfiguration = new CorsConfiguration(); 4 corsConfiguration.addAllowedHeader("*"); 5 corsConfiguration.addAllowedOrigin("*"); 7 corsConfiguration.addAllowedMethod("*"); 8 corsConfiguration.setMaxAge(3600L); // 預檢請求的有效期,單位為秒。 9 corsConfiguration.setAllowCredentials(true);// 是否支持安全證書(必需參數) 10 return corsConfiguration; 11 } 12 13 @Bean 14 public CorsFilter corsFilter() { 15 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 16 source.registerCorsConfiguration("/**", buildConfig()); 17 return new CorsFilter(source); 18 }
1. 跨域一般都會遇到能登陸但是不進授權的問題,因為shiro存儲認證信息是在登錄后存在瀏覽器的cookie中,訪問授權接口時會從cookie中取出認證信息進行認證,但是跨域cookie傳不到后台,用了另一種辦法,把認證信息存在請求頭中
https://www.cnblogs.com/elvinle/p/9272076.html-比較詳細
用了這種方式后把會話管理器注冊到DefaultWebSecurityManager ,這樣登錄后把認證信息放在響應頭中返回,前端取出來放在請求頭中發回來,就是從請求頭中直接拿認證信息了
@Bean(name = "sessionManager") public DefaultHeaderSessionManager sessionManager() { DefaultHeaderSessionManager sessionManager = new DefaultHeaderSessionManager(); // 設置session過期時間3600s sessionManager.setGlobalSessionTimeout(3600000L); sessionManager.setSessionValidationInterval(3600000L); return sessionManager; } @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setSessionManager(sessionManager()); securityManager.setRealm(myShiroRealm()); return securityManager; }
1.1 這里還有個小問題
https://segmentfault.com/q/1010000019535285---比較詳細
在使用跨域的時候前端不能直接從響應頭中取數據,為null。因為在使用跨域的方式進行前后端的交互時,瀏覽器只會使用默認的header。而認證信息是新添加的所以沒效果,需要告訴瀏覽器,這個請求頭數據要用,你得給前端才行
response.setHeader("key", token);
response.setHeader("Access-Control-Expose-Headers", "請求頭的key");
這是在登陸后,把認證信息放入響應頭后,添加這行代碼,瀏覽器才會知道你要用,才能拿到
2. 暫時沒二