赞
踩
前后端分离项目中,由于跨域,会导致复杂请求,即会发送 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”);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。