SpringSecurity
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.调试
1.默认自动开启拦截
@RestController
public class TestController {
@RequestMapping("/test")
public String test() {
return "hello world";
}
}
2.关闭默认拦截
//关闭默认拦截
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringsecuritydemoApplication {
public static void main(String[] args)
{
SpringApplication.run(SpringsecuritydemoApplication.class, args);
}
}
3.自定义账号密码
spring.security.user.name=cyrus
spring.security.user.password=123
3.配置认证
1.基于内存认证
1、创建配置类集成WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity //开启WebSecurity功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
2、重写configure方法
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
}
3、设置登录认证账号/密码
4、指定角色
auth.inMemoryAuthentication()//使用内存用户存储
.withUser("cyrus1")//用户名
.password(passwordEncoder().encode("123"))//密码
.roles();//身份
auth.inMemoryAuthentication()
.withUser("cyrus2")
.password(passwordEncoder().encode("123"))
.roles();
5、开启方法级安全
@EnableGlobalMethodSecurity(prePostEnabled = true)
//prePostEnabled = true : 拦截@PreAuthrize注解
6、配置方法级别权限控制
@PreAuthorize("hasAnyRole('admin')")
@PreAuthorize("hasAnyRole('normal','admin')")
具体代码
/**
* 配置
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("cyrus1")
.password(passwordEncoder().encode("123"))
.roles("admin");
auth.inMemoryAuthentication()
.withUser("cyrus2")
.password(passwordEncoder().encode("123"))
.roles("normal");
}
//BCrypt加密
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
/**
* 测试
*/
@RestController
public class TestController {
@RequestMapping("/hello")
public String hello() {
return "hello SpringSecurity";
}
@RequestMapping("/helloAdmin")
@PreAuthorize("hasAnyRole('admin')")
public String helloAdmin() {
return "hello admin";
}
@RequestMapping("/helloNormal")
@PreAuthorize("hasAnyRole('normal','admin')")
public String helloNormal() {
return "hello normal";
}
}
2.基于数据库认证
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 访问授权
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll() //请求放行所有
.antMatchers("/page/admin").hasRole("admin")
.antMatchers("/page/user").hasRole("user")
.antMatchers("/page/visitor").hasRole("visitor");
//没有权限默认到登陆页面
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("user").passwordParameter("pwd");
//防止网站攻击 get明文传续
http.csrf().disable(); //关闭csrf
//注销功能 注销跳转页面
http.logout().logoutSuccessUrl("/");
//记住我 登陆信息放入cookie 默认过期时间2星期
http.rememberMe().rememberMeParameter("remember");
//默认不能进行frame跳转,需要关闭!
http.headers().frameOptions().disable();
}
@Autowired
UserDetailServiceImpl userDetailService;
/**
* 权限认证
*/
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Member member = userMapper.getUserInfo(username);
if(member == null){
return null;
}else{
Collection<GrantedAuthority> authorities = new ArrayList<>();
if (member.getAuthority() == 1) {
authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
authorities.add(new SimpleGrantedAuthority("ROLE_user"));
authorities.add(new SimpleGrantedAuthority("ROLE_visitor"));
}
if (member.getAuthority() == 2) {
authorities.add(new SimpleGrantedAuthority("ROLE_user"));
authorities.add(new SimpleGrantedAuthority("ROLE_visitor"));
}
if (member.getAuthority() == 3) {
authorities.add(new SimpleGrantedAuthority("ROLE_visitor"));
}
//SpringSecurity登陆User信息
User user = new User(member.getUsername(),passwordEncoder.encode(member.getPassword()),authorities);
System.out.println("管理员信息:"+user.getUsername()+" "+passwordEncoder.encode(member.getPassword())+" "+user.getAuthorities());
return user;
}
}
}
4.整合thymeleaf
1.依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
2.引入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
3.使用
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 访问授权
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll() //请求放行所有
.antMatchers("/page/admin").hasRole("admin")
.antMatchers("/page/user").hasRole("user")
.antMatchers("/page/visitor").hasRole("visitor");
//没有权限默认到登陆页面
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("user").passwordParameter("pwd");
//防止网站攻击 get明文传续
http.csrf().disable(); //关闭csrf
//注销功能 注销跳转页面
http.logout().logoutSuccessUrl("/");
//记住我 登陆信息放入cookie 默认过期时间2星期
http.rememberMe().rememberMeParameter("remember");
}
/**
* 权限认证
*/
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("cyrus1")
.password(passwordEncoder().encode("123"))
.roles("admin","user","visitor");
auth.inMemoryAuthentication()
.withUser("cyrus2")
.password(passwordEncoder().encode("123"))
.roles("user","visitor");
auth.inMemoryAuthentication()
.withUser("cyrus3")
.password(passwordEncoder().encode("123"))
.roles("visitor");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
获取springsecurity登陆用户详情信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();