Spring security 安全框架的使用
@Configuration
public class SecutiryConfig extends WebSecurityConfigurerAdapter {
//权限管理
private static List requestList = null;
private static List staticList = null;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserInfoService userInfoService;
//静态代码块加载请求路径
static {
requestList = new ArrayList<>();
staticList = new ArrayList<>();
//请求
requestList.add("/");
requestList.add("/personLogin");
requestList.add("/index");
//静态资源
staticList.add("/css
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(requestList.toArray(new String[requestList.size()]))
.permitAll()//释放请求
.anyRequest()
.authenticated()//任何请求登录后才能访问
.and()
.formLogin()
.loginProcessingUrl("/login")//登录请求目标接口
.loginPage("/personLogin")//自定义登录页
.usernameParameter("username")//前端传过来的username
.passwordParameter("pwd")//前端传过来的username
//登录成功后访问
.successForwardUrl("/index")
//登陆成功后 处理失败的请求
.failureForwardUrl("/fail")
//安全退出
.and()
.logout()
.logoutSuccessUrl("/index")//安全退出后.跳转到首页
//防止跨域攻击
.and()
.csrf()
.disable();
}
//用户管理
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println(passwordEncoder.encode("123"));
// auth.inMemoryAuthentication()
// .withUser("admin")
// .password(passwordEncoder.encode("123"))
// .roles("admin","user");
auth.userDetailsService(userInfoService);
}
//静态资源管理
@Override
public void configure(WebSecurity web) throws Exception {
String[] statics = staticList.toArray(new String[staticList.size()]);
web.ignoring().antMatchers(statics);
}
//密码加密对象
//用于加密密码和校验密码
@Bean
public PasswordEncoder createPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
我们需要通过请求数据库查询用户及角色信息 service 必须实现UserDetailService接口重写loadUserByUsername(String s)方法 返回一个User对象
@Service
public class UserInfoService implements UserDetailsService {
@Autowired
private UserInfoMapper userInfoMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userInfoMapper.login(username);
if (userInfo == null){
throw new UsernameNotFoundException("用户名不存在");
}
//查询角色
List roleList = new ArrayList<>();
for (RoleInfo roleInfo : userInfo.getRoleInfoList()) {
//如果数据库中角色信息 没有添加 ROLE_ 前缀 我们需要手动添加
//安全框架 默认的一个前缀 可以覆盖不能为null
roleList.add(new SimpleGrantedAuthority("ROLE_"+roleInfo.getRoleName()));
}
//构建一个user对象
return User.builder()
.username(userInfo.getUsername())
.password(userInfo.getPassword())
.authorities(roleList)
.build();
}
}



