一.定义

  所谓的授权,就是用户如果要访问某一个资源,我们要去检查用户是否具备这样的权限,如果具备就允许访问,如果不具备,则不允许访问。

 

二.准备测试用户(由于没有连接数据库)

  1.基于内存配置测试用户

    

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("test1")   //用户名
            .password("123456")      //密码
       .roles("admin") //角色 .and() .withUser("test2") .password("123456") .roles("user"); }

   2.实现UserDetailService 接口  重写loadUserByUserNmae

    

public class SsoUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        return new User(username, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    }    
}

  3.还可以通过重写 WebSecurityConfigurerAdapter 中的 userDetailsService 方法来提供一个 UserDetailService 实例进而配置多个用户:

  

@Bean
protected UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(User.withUsername("test1").password("123456").roles("admin").build());
    manager.createUser(User.withUsername("test2").password("123456").roles("user").build());
    return manager;
}

 

三.测试接口

  

@RestController
public class HelloController {
  //  /hello 是任何人都可以访问的接口
  @GetMapping("/hello") 

  public String hello() {
    return "hello";
    }
  // /admin/hello 是具有 admin 身份的人才能访问的接口
    @GetMapping("/admin/hello")
    public String admin() {
        return "admin";
    }
  

   // /user/hello 是具有user身份能访问的接口,但是user能访问的资源,admin都可以访问 (角色继承) @GetMapping(
"/user/hello") public String user() { return "user"; } }

    

四.配置

@Configuration
public class SsoSecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("admin")    //如果请求路径满足 /admin/** 格式,则用户需要具备 admin 角色。
            .antMatchers("/user/**").hasRole("user")     //如果请求路径满足 /user/** 格式,则用户需要具备 user 角色
            .anyRequest().authenticated()               //剩余的其他格式的请求路径,只需要认证(登录)后就可以访问。
            .and() 
  }
}

    Ant 风格的路径匹配符

通配符含义
** 匹配多层路径
* 匹配一层路径
? 匹配任意单个字符

 

 

五.角色继承

  定义:要实现所有 user 能够访问的资源,admin 都能够访问

  我们只需要在继承了WebSecurityConfigurerAdapter 类的类中添加如下代码来配置角色继承关系即可:

  

@Bean
RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
    hierarchy.setHierarchy("ROLE_admin > ROLE_user");   //表示 ROLE_admin 自动具备 ROLE_user 的权限。
    return hierarchy;
}

  【】在配置时,需要给角色手动加上 ROLE_ 前缀

 

posted on 2020-04-26 14:24  印记XP  阅读(225)  评论(0编辑  收藏  举报