学习笔记——springCloud OAuth2+JWT(微服务统一认证)

架构图:
学习笔记——springCloud OAuth2+JWT(微服务统一认证)_第1张图片
1,构建Oauth2Server认证服务端

  • pom依赖
<!--oauth2依赖-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-oauth2</artifactId>
      <exclusions>
         <exclusion>                                                               <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
         </exclusion>
      </exclusions>
  </dependency>
  <dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.1.11.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.3.4.RELEASE</version>
  </dependency>
  • 启动类(与普通springBoot项目一致,无特殊化)
  • 创建OauthServer配置类

/**
 * OauthServer配置类
 * 1,继承AuthorizationServerConfigurerAdapter类
 * 2,重写方法该父类的方法(三个configure方法)
 * 3,开启注解  @EnableAuthorizationServer 开启认证服务器功能
 * @author: CoffeeBull
 * @date:2020-05-14
 */
@Configuration
@EnableAuthorizationServer
public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 打开对外开放的api接口,配置接口权限
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        //允许客户端表单认证
        security.allowFormAuthenticationForClients()
                //开启端口/oauth/token_key访问权限
                .tokenKeyAccess("permitAll")
                //开启端口/oauth/token_key访问权限
                .checkTokenAccess("permitAll");
    }

    /**
     * 配置客户端的详情信息,此处客户端信息可从数据库读取
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        //设置客户端信息存储的位置,比如内存或数据库
        clients.inMemory()
                //添加一个客户端,指定其clientId为user_service
                .withClient("user_service")
                //指定客户端的密码
                .secret("123456")
                //指定客户端能访问的资源id清单
                .resourceIds("user")
                //指定认证类型/令牌颁发模式
                .authorizedGrantTypes("password","refresh_token")
                //客户端的权限范围
                .scopes("all");
    }

    /**
     * 配置令牌的访问断点和令牌服务
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        //指定令牌的存储方式
        endpoints.tokenStore(getTokenStore())
                //token生成的配置,比如有效时间等
                .tokenServices(getAuthorizationServerTokenServices())
                //指定认证管理器
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
    }

    /**
     * 令牌的存储方式
     * @return
     */
    public TokenStore getTokenStore(){
        return new InMemoryTokenStore();
    }

    /**
     * 创建token服务,设置token配置信息
     * @return
     */
    public AuthorizationServerTokenServices getAuthorizationServerTokenServices(){
        //默认实现
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        //是否开启令牌刷新
        defaultTokenServices.setSupportRefreshToken(true);
        //设置令牌有效期(一般设置2小时)
        defaultTokenServices.setAccessTokenValiditySeconds(2*60*60);
        //设置刷新令牌的有效期(2天)
        defaultTokenServices.setRefreshTokenValiditySeconds(172800);
        return defaultTokenServices;
    }
}
  • 创建SecurityConfig安全配置类
/**
 * 安全配置类
 * 1,继承WebSecurityConfigurerAdapter
 * 2,重写configure方法
 * @author: CoffeeBull
 * @date:2020-05-14
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 创建一个认证管理对象放到容器中
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 设置密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);  此处一定要注释掉!!
        //此处可以去关联数据库取出用户信息  new User等同于一条用户记录表数据
        UserDetails user = new User("admin","123456",new ArrayList<>());
        auth.inMemoryAuthentication()
                .withUser(user)
                .passwordEncoder(passwordEncoder);
    }
}

测试检验url:
localhost:9999/oauth/token?client_secret=123456&grant_type=password&username=admin&password=123456&client_id=user_service

2,构建资源服务器

  • 引入依赖
                                                    org.springframework.security.oauth
    spring-security-oauth2
    2.3.4.RELEASE
 
  • 编写配置类
@Configuration
@EnableResourceServer
@EnableWebSecurity  // 开启web访问安全
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
    /**
     * 配置需要认证的接口
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //设置session的创建策略
       http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
               .and()
               .authorizeRequests()
               //配置前缀为/api/user需要被认证
               .antMatchers("/api/user/test").authenticated()
               //其他请求直接放行
               .anyRequest().permitAll();
    }

    /**
     * 用于定义资源服务器向远程服务器发起请求及token检验配置
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //当前资源服务器id,与认证服务器上的对应
        resources.resourceId("user");
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        //设置校验token的url
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:9999/oauth/check_token");
        //设置携带的clientId
        remoteTokenServices.setClientId("user_service");
        //设置携带的密码
        remoteTokenServices.setClientSecret("123456");
        resources.tokenServices(remoteTokenServices);

    }
}

测试url:
获取令牌:
localhost:9999/oauth/token?client_secret=123456&grant_type=password&username=admin&password=123456&client_id=user_service
通过令牌访问:
http://localhost:8080/api/user/test?access_token=f4424f9b-1cce-4b5d-b3e8-5814ffc3e981
待续…(最近有点忙,JWT的改造可能要下周更新了)

你可能感兴趣的:(学习笔记——springCloud OAuth2+JWT(微服务统一认证))