Spring Boot + Vue + Shiro 实现前后端分离,写得太好了!
共 3566字,需浏览 8分钟
·
2021-10-17 14:02
阅读本文大概需要 8 分钟。
作者:_Yufan
来源:www.cnblogs.com/yfzhou/p/9813177.html
一、前后端分离思想
二、后端 Springboot
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public JSONResult addClient(@RequestBody String param) {
JSONObject jsonObject = JSON.parseObject(param);
String task = jsonObject.getString("task");
List
三、前端 Vue + ElementUI + Vue router + Vuex + axios + webpack
https://cn.vuejs.org/v2/guide/ https://github.com/PanJiaChen/vue-admin-template/blob/master/README-zh.md https://github.com/PanJiaChen/vue-element-admin
XMLHttpRequest 会遵守同源策略 (same-origin policy). 也即脚本只能访问相同协议 / 相同主机名 / 相同端口的资源, 如果要突破这个限制, 那就是所谓的跨域, 此时需要遵守 CORS(Cross-Origin Resource Sharing) 机制。
@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", "*");
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");
}
https://blog.csdn.net/cc1314_/article/details/78272329
并且注意,在 F12 看到的 js 提示错误的域名,是 js 写的那个域名,并不是代理后的域名。(l 楼主就遇到这个问题,后端地址缺少了查询参数,代理设置为后端地址,然而 F12 看到的错误依然还是本地的域名,并不是代理后的域名)
四、前后端分离项目中集成 shiro
blog.csdn.net/u013615903/article/details/78781166
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();
Mapmap= new HashMap<>();
map.put("code", 702);
map.put("msg", "未登录");
writer.write(JSON.toJSONString(map));
writer.close();
return false;
}
}
@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");
//
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);
MapfilterChainDefinitionMap = 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);
//自定义过滤器
MapfilterMap = 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;
}
}
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);
}
}
}
五、部署项目
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String index() {
return "/index";
}
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();
Mapmap= new HashMap<>();
map.put("code", 702);
map.put("msg", "未登录");
writer.write(JSON.toJSONString(map));
writer.close();
return false;
}
}
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅