這篇文章給大家介紹怎么在shiro中整合springboot實現(xiàn)前后端分離,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
成都創(chuàng)新互聯(lián)網(wǎng)絡(luò)公司擁有10多年的成都網(wǎng)站開發(fā)建設(shè)經(jīng)驗,上1000+客戶的共同信賴。提供成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站開發(fā)、網(wǎng)站定制、賣友情鏈接、建網(wǎng)站、網(wǎng)站搭建、成都響應(yīng)式網(wǎng)站建設(shè)公司、網(wǎng)頁設(shè)計師打造企業(yè)風格,提供周到的售前咨詢和貼心的售后服務(wù)
1、shiro整合springboot的配置
package com.hisi.config; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import org.apache.shiro.session.mgt.eis.MemorySessionDAO; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.hisi.shiro.LoginAuthorizationFilter; import com.hisi.shiro.RestFilter; import com.hisi.shiro.UserRealm; @Configuration public class ShiroConfig { /** * 安全管理器 * @param realm * @return */ @Bean public DefaultWebSecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(userRealm()); securityManager.setSessionManager(sessionManager()); return securityManager; } /** * Realm配置 * @return */ @Bean public UserRealm userRealm(){ return new UserRealm(); } /** * SessionDAO配置 * @return */ @Bean public SessionDAO sessionDAO(){ return new MemorySessionDAO(); } /** * sessionManager配置 * @param sessionDAO * @return */ @Bean public DefaultWebSessionManager sessionManager(){ DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(sessionDAO()); return sessionManager; } /** * shiroFilter配置 * @param securityManager * @return */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){ ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager()); Map<String, Filter> filters = new LinkedHashMap<String, Filter>(); filters.put("token", new LoginAuthorizationFilter()); filters.put("corsFilter", new RestFilter()); shiroFilter.setFilters(filters); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); filterChainDefinitionMap.put("/user/login", "corsFilter,anon"); filterChainDefinitionMap.put("/user/logout", "corsFilter,anon"); filterChainDefinitionMap.put("/user/**", "corsFilter,token"); shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilter; } /** * 保證實現(xiàn)了Shiro內(nèi)部lifecycle函數(shù)的bean執(zhí)行 */ @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } /** * 啟用shrio授權(quán)注解攔截方式,AOP式方法級權(quán)限檢查 */ @Bean @DependsOn(value = "lifecycleBeanPostProcessor") //依賴其他bean的初始化 public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { return new DefaultAdvisorAutoProxyCreator(); } /** * 加入注解的使用,不加入這個注解不生效 使用shiro框架提供的切面類,用于創(chuàng)建代理對象 * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
2、這里配置的兩個過濾器RestFilter和LoginAuthorizationFilter,RestFilter是用于解決前后端分離時的跨域問題,服務(wù)端在響應(yīng)頭設(shè)置可以接受的請求參數(shù)
package com.hisi.shiro; import java.io.IOException; import java.util.Optional; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 前后端分離RESTful接口過濾器 * * @author xuguoqin * */ public class RestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = null; if (request instanceof HttpServletRequest) { req = (HttpServletRequest) request; } HttpServletResponse res = null; if (response instanceof HttpServletResponse) { res = (HttpServletResponse) response; } if (req != null && res != null) { //設(shè)置允許傳遞的參數(shù) res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); //設(shè)置允許帶上cookie res.setHeader("Access-Control-Allow-Credentials", "true"); String origin = Optional.ofNullable(req.getHeader("Origin")).orElse(req.getHeader("Referer")); //設(shè)置允許的請求來源 res.setHeader("Access-Control-Allow-Origin", origin); //設(shè)置允許的請求方法 res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS"); } chain.doFilter(request, response); } @Override public void destroy() { } }
前者ajax請求的時候應(yīng)該帶上參數(shù)
$.ajax({ type: "GET", url: url, xhrFields: { withCredentials: true // 攜帶跨域cookie }, processData: false, success: function(data) { console.log(data); } });
3、LoginAuthorizationFilter主要是對未登錄的用戶進行過濾然后返回json數(shù)據(jù)給前端,之前遇到的問題就是shiro配置的loginUrl會導致出現(xiàn)302的問題,在前后端分離的項目中,頁面的跳轉(zhuǎn)應(yīng)該由前端來進行控制,這里前端使用的是vue框架,我需要對shiro中未登錄的過濾器FormAuthenticationFilter進行重構(gòu)
package com.hisi.shiro; import java.io.IOException; import java.io.PrintWriter; import java.util.Set; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.CollectionUtils; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.filter.authz.AuthorizationFilter; import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.fastjson.JSONObject; import com.commons.model.YfpjResult; import com.hisi.mapper.HisiUserMapper; import com.hisi.model.HisiUser; import com.hisi.util.Constant; import com.hisi.util.UserAuthStatusEnum; /** * shiro未登錄反回狀態(tài)碼 * @author xuguoqin * @date 2018年5月10日 * @version 1.0 */ public class LoginAuthorizationFilter extends FormAuthenticationFilter { /** * 這個方法是未登錄需要執(zhí)行的方法 */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Subject subject = getSubject(request, response); if (subject.getPrincipal() == null) { //設(shè)置響應(yīng)頭 httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType("application/json"); //設(shè)置返回的數(shù)據(jù) YfpjResult result = YfpjResult.build(UserAuthStatusEnum.UNLOGIN.getCode(), UserAuthStatusEnum.UNLOGIN.getMsg()); //寫回給客戶端 PrintWriter out = httpResponse.getWriter(); out.write(JSONObject.toJSONString(result)); //刷新和關(guān)閉輸出流 out.flush(); out.close(); } else { //設(shè)置響應(yīng)頭 httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType("application/json"); //設(shè)置返回的數(shù)據(jù) YfpjResult result = YfpjResult.build(UserAuthStatusEnum.UNAUTH.getCode(), UserAuthStatusEnum.UNAUTH.getMsg()); //寫回給客戶端 PrintWriter out = httpResponse.getWriter(); out.write(JSONObject.toJSONString(result)); //刷新和關(guān)閉輸出流 out.flush(); out.close(); } return false; } }
關(guān)于怎么在shiro中整合springboot實現(xiàn)前后端分離就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
文章題目:怎么在shiro中整合springboot實現(xiàn)前后端分離
URL地址:http://muchs.cn/article18/piohgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、網(wǎng)站導航、外貿(mào)建站、微信公眾號、網(wǎng)站策劃、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)