SpringBoot笔记--Shiro解决跨域问题
2021-06-16 本文已影响0人
Sunny旋律
一、Shiro配置了anon
不会被拦截的接口
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
SessionCheckFilter sessionCheckFilter = new SessionCheckFilter();
Map<String, Filter> cumstomfilterMap = new HashMap<>();
//注意:map里面key值必须要和下面的/**里的value对应上才能使用自定义的过滤器
cumstomfilterMap.put("authc", sessionCheckFilter);
Map<String, String> filterMap = new LinkedHashMap<>();
// 配置不会被拦截的url
filterMap.put("/user/login", "anon");
filterMap.put("/**", "authc");
shiroFilter.setFilterChainDefinitionMap(filterMap);
shiroFilter.setFilters(cumstomfilterMap);
return shiroFilter;
}
可直接在controller或者接口处添加
@CrossOrigin
注解,二选一即可。如下所示
@CrossOrigin
public class UserController {
@CrossOrigin
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Object login(HttpServletResponse response, @RequestBody LoginReq loginReq) {
//...代码省略
}
二、Shiro配置了authc
拦截需要认证的接口
例如
/user/info
接口,没有配置过滤,就会被拦截,这个时候无论是在Controller上还是在接口实现上配置@CrossOrigin
,都不会生效。这个时候需要做如下配置
@Component
public class SessionCheckFilter extends UserFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
String token = WebUtils.toHttp(request).getHeader(ShiroSessionManager.AUTHORIZATION);
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
//解决跨域问题
if ("OPTIONS".equals(httpRequest.getMethod())){
httpResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);;
return true;
}
httpResponse.setCharacterEncoding("UTF-8");
String responseJson;
if (StringUtils.isEmpty(token)) {
responseJson = JSON.toJSONString(ApiResult.failure(ResponseCode.USER_TOKEN_NULL_ERROR));
} else {
responseJson = JSON.toJSONString(ApiResult.failure(ResponseCode.USER_TOKEN_ERROR));
}
httpResponse.getWriter().print(responseJson);
httpResponse.getWriter().flush();
httpResponse.getWriter().close();
return false;
}
}