跨域问题基础配置
跨域的本质是响应头问题,只要加上下述的响应头即可解决跨域。(下述1、配置跨域
中的代码是通过aop来实现该功能的一种方式)
1、配置跨域
正常的跨域配置
@Component
public class CORSInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS");
response.setCharacterEncoding("utf8");
response.setContentType("text/json;charset = UTF-8");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private CORSInterceptor corsInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor).addPathPatterns("/**");
}
}
//路由的话直接使用的@CrossOrigin注解
@CrossOrigin
@RestController
@RequestMapping("/operationLog2D")
public class OperationLogController {
}
2、SpringSecurity配置
关键是.and().cors()
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()//可以自定义哪些被保护哪些不被保护
.anyRequest().permitAll()//所有请求都可以直接通过
.and().cors()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
我遇到的问题
完成了上面的步骤之后还是有跨域的报错。。。。
仔细检查了检查发现应该是UserDetails
的问题,就是我之前准备用SpringSecurity
自带的那个认证做登录授权,但是由于时间有限,在整合jwt那个部分没什么时间研究就放弃网上的方法了,之后的认证授权没有用到UserDetailsService
这个继承了UserDetails
的实现类(按着之前教程的说法,springsecurity自带的认证会现在配置文件.yml
或者SecurityConfig
中找,如果没找到的话就会去找UserDetailsService
或者继承了这个类的自定义类,在这个实现类中获取表单提交的账号密码完成认证操作 )。
然后我就试了试把和这个相关的地方注释掉,终于不报跨域的错误了。
被注释的代码如下
注释了所有
//package com.operative.user.service;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.operative.base.utils.WrapperUtil;
//import com.operative.role.entity.Role;
//import com.operative.role.mapper.RoleMapper;
//import com.operative.user.mapper.UserMapper;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.stereotype.Service;
//
//import java.util.ArrayList;
//import java.util.List;
//@Service("userDetailsService")
//public class MyUserDetailsService implements UserDetailsService {
// @Autowired
// private UserMapper userMapper;
// @Autowired
// private RoleMapper roleMapper;
//
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// final com.operative.user.entity.User user = userMapper.selectOne(WrapperUtil.getQueryWrapper("username", username));
// if (user==null){
// throw new UsernameNotFoundException("用户名不存在");
// }
// //获取权限
// final List<GrantedAuthority> list = getAuthorities(user);
// return new User(user.getUsername(),user.getPassword(),list);
// }
//
//
// /**
// * 获取登录用户权限
// * @return List<GrantedAuthority>
// */
// public List<GrantedAuthority> getAuthorities(com.operative.user.entity.User user) {
//
// final List<GrantedAuthority> list = new ArrayList<>();
//
// final String roleIds = user.getRoleIds();//获取所有角色id数组
// final List<Integer> roleIdList = JSON.parseArray(roleIds, Integer.class);
// for (Integer roleId : roleIdList) {//循环角色id
// final Role role = roleMapper.selectOne(WrapperUtil.getQueryWrapper("id", roleId));
// final String permissionIds = role.getPermissionIds();
// final List<Integer> perIdList = JSON.parseArray(permissionIds, Integer.class);
// for (Integer perId : perIdList) {//循环角色的权限id
//
// final SimpleGrantedAuthority authId = new SimpleGrantedAuthority(perId.toString());
// if (!list.contains(authId)) {//去重
// list.add(authId);
// }
// }
// }
// System.out.println("获取登录用户权限");
// for (GrantedAuthority grantedAuthority : list) {
// System.out.println("_______+++++" + grantedAuthority);
// }
// return list;
// }
//
//}
注释了所有下面两个部分
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @Autowired
// private UserDetailsService userDetailsService;//通过service后面的名字注入进来
// /**
// * 设置自己定义的登录实现类
// * @param auth
// * @throws Exception
// */
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());//这里把通过Bean创建的对象向注入进去
// }
}
有时间一定要再仔细看看,看看是什么原因