Spring Security + OAuth2 - 黑马程序员(5. 资源服务搭建与测试)学习笔记 - Go语言中文社区

Spring Security + OAuth2 - 黑马程序员(5. 资源服务搭建与测试)学习笔记


上一篇:Spring Security + OAuth2(4. OAuth 的四种模式)

下一篇:Spring Security + OAuth2(6. JWT 令牌)

1. 搭建环境

  • 当前操作都是在 distributed-security-order 项目中进行的
  • 之前在第 2 节中以及将所有环境都搭建完成了,所以这里就不多说了。
  • 还是先上一下目录结构
    在这里插入图片描述

1.1 配置资源

  • controller 包下编写 OrderController

  • 此controller表示订单资源的访问类:

    @RestController
    public class OrderController {
    
        @GetMapping(value = "/r1")
        @PreAuthorize("hasAuthority('p1')")//拥有p1权限方可访问此url
        public String r1(){
            //获取用户身份信息
            UserDTO  userDTO = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return userDTO.getFullname()+"访问资源1";
        }
    }
    

1.2 配置资源服务

  • Config 包下,编写资源服务的配置 ResouceServerConfig

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    
    @Configuration
    @EnableResourceServer
    public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
    
        public static final String RESOURCE_ID = "res1";
        
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(RESOURCE_ID)//资源 id
                    .tokenServices(tokenService())//验证令牌的服务
                    .stateless(true);
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
    
            http
                    .authorizeRequests()
                    .antMatchers("/**").access("#oauth2.hasScope('all')")
                    .and().csrf().disable()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }
    

简单说明:

  • @EnableResourceServer 注解到一个 @Configuration 配置类上,并且必须使用ResourceServerConfigurer 这个配置对象来进行配置(可以选择继承自ResourceServerConfigurerAdapter 然后覆写其中的方法,参数就是这个对象的实例),下面是一些可以配置的属性:

    1. ResourceServerSecurityConfigurer
      其中主要包括:

      • tokenServices:ResourceServerTokenServices 类的实例,用来实现令牌服务。
      • tokenStore:TokenStore类的实例,指定令牌如何访问,与tokenServices配置可选
      • resourceId:这个资源服务的ID,这个属性是可选的,但是推荐设置并在授权服务中进行验证。
      • 其他的拓展属性例如 tokenExtractor 令牌提取器用来提取请求中的令牌。
    2. HttpSecurity

      • 请求匹配器,用来设置需要进行保护的资源路径,默认的情况下是保护资源服务的全部路径。
      • 通过http.authorizeRequests()来设置受保护资源的访问规则
      • 其他的自定义权限保护规则通过 HttpSecurity 来进行配置。
  • @EnableResourceServer 注解自动增加了一个类型为 OAuth2AuthenticationProcessingFilter过滤器链

1.3 配置令牌验证

  • 通常情况下,资源服务和权限验证服务不在同一个模块中,所以就需要用到远程验证。

  • Config 包下的 ResouceServerConfig 方法中添加:

    //资源服务令牌解析服务
    @Bean
    public ResourceServerTokenServices tokenService() {
        //使用远程服务请求授权服务器校验token,必须指定校验token 的url、client_id,client_secret
        RemoteTokenServices service=new RemoteTokenServices();
        service.setCheckTokenEndpointUrl("http://localhost:53020/uaa/oauth/check_token");
        service.setClientId("c1");
        service.setClientSecret("secret");
        return service;
    }
    

    在这里插入图片描述

1.4 添加基于 HTTP 请求的安全访问控制

  • 在 Config 包下编写:WebSecurityConfig

    @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        //安全拦截机制(最重要)
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过
                    .anyRequest().permitAll();//除了/r/**,其它的请求可以访问
        }
    }
    

2. 测试资源服务

  1. 申请令牌
    在上一节中介绍了四种获得令牌的方式,这里使用 用户名密码的方式进行获取。
    在这里插入图片描述

  2. 请求资源

    按照oauth2.0协议要求,请求资源需要在 头文件 header 中携带token,如下:

    参数名称为:Authorization
    参数值为:Bearer token值(这里的 Bearer 是要写在参数值的开头的,且需要有一个空格隔开)

  • 如果 Token 值错误的话,结果如下
    在这里插入图片描述
  • 令牌信息正确的话就可以得到在 Controller 中编写的信息。
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_44449838/article/details/114805454
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢