配置Security核心配置类
将WebSecurityConfig放在auth包下
右击鼠标-->点击Generate... -->点击Override Methods... 选择下面的三个configure
禁用防护:
http.csrf().disable()
禁用Session的配置:
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
禁用缓存:
.headers().cacheControl();
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity//开启权限注解控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
用户登录认证
理解思路:
根据用户名查询用户信息,判断用户名是否存在,不存在则给出异常,存在说明没毛病。
存在就根据用户的id去数据库查询他所拥有的角色身份,用每一个的角色身份查出所拥有的权限,这可以用sql语句一次性查出,也可以分两步查询,将权限编码存储在权限集authorities中
返回值 UserDetails 是一个接口 ,有两个参数构造,一个是三个参数的构造方法,另一个是七个的构造方法
String getPassword( ); 获取密码
String getUsername( ); 获取用户名
Collection<? extends GrantedAuthority> getAuthorities( ); 获取所有权限
boolean isAccountNonExpired( ); 是否账号过期
boolean isAccountNonLocked( ); 是否账号被锁定
boolean isCredentialsNonExpired( ); 凭证(密码)
boolean isEnabled( ); 是否可用
UserDetalisServiceImpl
package com.jiangzhu.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiangzhu.entity.SysMenu;
import com.jiangzhu.entity.SysUser;
import com.jiangzhu.mapper.SysUserMapper;
import com.jiangzhu.service.SysMenuService;
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
public class UserDetalisServiceImpl implements UserDetailsService {
@Autowired
private SysUserMapper userMapper;
@Autowired
private SysMenuService menuService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//查询用户是否存在
Qu