Springboot整合SpringSecurity
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.配置类Config
继承WebSecurityConfigurerAdapter
因为我们会重载其中的configure方法,注意configure方法会有不同的参数,不同参数的configure方法的作用一般不同
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
void configure(AuthenticationManagerBuilder auth)
该方法用来提供认证用户
注释掉的部分是另一种引入认证用户的方法,在这里采用了从数据库中的方法。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
// BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// String password = passwordEncoder.encode("qp");
// auth.inMemoryAuthentication().withUser("qp").password(password).roles("admin");
auth.userDetailsService(userDetailsService).passwordEncoder(password());
}
控制访问部分
我们发现其方法名也是configure
@Override
protected void configure(HttpSecurity http) throws Exception{
http.exceptionHandling().accessDeniedPage("/unauth");
http.logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccess").permitAll();
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/user/login")
.defaultSuccessUrl("/test").permitAll()
.and().authorizeRequests()
.antMatchers("/user/register","/register.html","/comments/game/all")
.permitAll()
// .antMatchers("/test").hasAuthority("users")
.anyRequest().authenticated()
.and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60).userDetailsService(userDetailsService)
.and().csrf().disable(); //关闭csrf防护
}
设置组件
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
3.Service编写
导入usermapper
@Autowired
private UsersMapper usersMapper;
重载方法,将指定用户名的用户从数据库中读取出来,并为其绑定角色
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper();
wrapper.eq("username",username);
Users user = usersMapper.selectOne(wrapper);
if (user == null) {
throw new UsernameNotFoundException("用户不存在!");
}
List<GrantedAuthority> auths =
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admins");
return new User(user.getUsername(),
user.getPassword(),auths);
}
Controller中设置访问权限
在此处展示一种设置方法
@ResponseBody
@RequestMapping(value = "/test")
@Secured({"ROLE_admins"})
public Object testHello(HttpServletRequest request){
return "OK";
}
注意到这里是ROLE_admins和Service中对应
原因在于Security源码在使用这种方法进行权限判定时,有前缀ROLE_的判断