1.方法安全
在启动类上添加注解
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
创建service
@Service
public class MethodService {
@PreAuthorize("hasRole('admin')")
public String admin(){
return "hello admin";
}
@Secured("ROLE_user")
public String user(){
return "hello user";
}
@PreAuthorize("hasAnyRole('admin','user')")
public String hello(){
return "hello hello";
}
}
创建controller测试
@GetMapping("/hello1")
public String hello1(){
return methodService.admin();
}
@GetMapping("/hello2")
public String hello2(){
return methodService.user();
}
@GetMapping("/hello3")
public String hello3(){
return methodService.hello();
}
2.基于数据库的安全管理
1.创建springboot项目
引入这几个依赖
2.配置pom.xml
在mysql换上自己的版本
添加Alibaba的连接池依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.14</version>
</dependency>
3.配置application.properties数据库的参数
spring.datasource.username=root
spring.datasource.password=1024
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
5.配置bean,User和Role
User:
//需要实现一个接口
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private boolean enable;
private boolean lock;
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String getUsername() {
return username;
}
//账户是否未过期
@Override
public boolean isAccountNonExpired() {
return true;
}
//账户是否未锁定
@Override
public boolean isAccountNonLocked() {
return !lock;
}
//凭证是否未过期
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enable;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities=new ArrayList<>();
for (Role role:roles){
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
System.out.println(1222);
this.password = password;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public void setLock(boolean lock) {
this.lock = lock;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", enable=" + enable +
", lock=" + lock +
", roles=" + roles +
'}';
}
}
Role:
public class Role {
private Integer id;
private String name;
private String nameZh;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameZh() {
return nameZh;
}
public void setNameZh(String nameZh) {
this.nameZh = nameZh;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
", nameZh='" + nameZh + '\'' +
'}';
}
}
6.配置mapper接口
(1)在启动类上添加注解
表示mapper的扫描位置
@MapperScan("top.chenyp.mapper")
(2)编写mapper接口
public interface UserMapper {
@Select("select *from user where username=#{username};")
User loadUserByUsername(String username);
@Select("select * from role where id in (select rid from user_role where uid=#{id})")
List<Role> getUserRolesById(Integer id);
}
7.编写service
Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user=userMapper.loadUserByUsername(username);
if (user==null){
throw new UsernameNotFoundException("用户不存在!");
}
user.setRoles(userMapper.getUserRolesById(user.getId()));
return user;
}
}
8.编写config配置权限管理类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/dba/**").hasRole("dba")
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasRole("user")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.csrf().disable();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
9.编写controller类进行测试
@RestController
public class UserController {
@GetMapping("/hello")
public String hello(){
return "hello security!";
}
@GetMapping("/admin/hello")
public String admin(){
return "hello admin!";
}
@GetMapping("/dba/hello")
public String dba(){
return "hello dba!";
}
@GetMapping("/user/hello")
public String user(){
return "hello user!";
}
}
10.总结:
这样就配置好了,各个用户,只能访问拥有这个权限的路径。