Spring Cloud认证授权收藏

微服务架构 | 7.1 基于 OAuth2 的安全认证

2022-02-02  本文已影响0人  多氯环己烷

前言

《Spring Microservices in Action》
《Spring Cloud Alibaba 微服务原理与实战》
《B站 尚硅谷 SpringCloud 框架开发教程 周阳》

OAuth2 是一个基于令牌的安全验证和授权框架。他允许用户使用第三方验证服务进行验证。 如果用户成功进行了验证, 则会出示一个令牌,该令牌必须与每个请求一起发送。然后,验证服务可以对令牌进行确认;


1. OAuth2 基础知识

1.1 安全性的 4 个组成部分

1.2 OAuth2 的工作原理

Oauth执行流程.png

1.3 OAuth2 规范的 4 种类型的授权

1.4 OAuth2 的优势

1.5 OAuth2 核心原理

1.6 JSON Web Token

2. 建立 OAuth2 服务器

2.1 引入 pom.xml 依赖文件

<!--security 通用安全库-->
<dependency> 
    <groupid>org.springframework.cloud</groupid> 
    <artifactid>spring-cloud-security</artifactid> 
</dependency> 
<!--oauth2.0-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

2.2 主程序类上添加注解

2.3 添加受保护对象的端点

在 controller 包下;

/**
 * 用户信息校验
 * 由受保护服务调用,确认 OAuth2 访问令牌,并检索访问受保护服务的用户所分配的角色
 * @param OAuth2Authentication 信息
 * @return 用户信息
 */
@RequestMapping(value = { "/user" }, produces = "application/json")
public Map<String, Object> user(OAuth2Authentication user) {
    Map<String, Object> userInfo = new HashMap<>();
    userInfo.put("user", user.getUserAuthentication().getPrincipal());
    userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
    return userInfo;
}

2.4 定义哪些应用程序可以使用服务

在 config 包下;

2.4.1 使用 JDBC 存储

@Configuration
//继承 AuthorizationServerConfigurerAdapter 类
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    //定义哪些客户端将注册到服务
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //JDBC存储:
        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT); //设置我们的自定义的sql查找语句
        clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT); //设置我们的自定义的sql查找语句
        clients.withClientDetails(clientDetailsService); //从 jdbc 查出数据来存储
    }
    
    @Override
    //使用 Spring 提供的默认验证管理器和用户详细信息服务
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }
}
public interface SecurityConstants {
    /**
     * sys_oauth_client_details 表的字段,不包括client_id、client_secret
     */
    String CLIENT_FIELDS = "client_id, client_secret, resource_ids, scope, "
            + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
            + "refresh_token_validity, additional_information, autoapprove";

    /**
     *JdbcClientDetailsService 查询语句
     */
    String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + " from sys_oauth_client_details";

    /**
     * 默认的查询语句
     */
    String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";

    /**
     * 按条件client_id 查询
     */
    String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";
}

2.4.2 使用内存储存

@Configuration
//继承 AuthorizationServerConfigurerAdapter 类
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    //定义哪些客户端将注册到服务
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")  //名称
                .secret("thisissecret")  //密钥
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")  //授权类型列表
                .scopes("webclient", "mobileclient");  //获取访问令牌时可以操作的范围
    }

    @Override
    //使用 Spring 提供的默认验证管理器和用户详细信息服务
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }
}

2.5 为应用程序定义用户 ID、密码和角色

在 config 包下:

@Configuration
@EnableWebSecurity
//扩展核心 Spring Security 的 WebSecurityConfigurerAdapter
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    //用来处理验证
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //处理返回用户信息
    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }
    
    //configure() 方法定义用户、密码与角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("john.carnell").password("password1").roles("USER")
                .and()
                .withUser("william.woodward").password("password2").roles("USER", "ADMIN");
    }
}

2.6 通过发送 POST 请求验证用户

3. 使用 OAuth2 建立并保护服务资源

3.1 引入 pom.xml 依赖文件

<!--security 通用安全库-->
<dependency> 
    <groupid>org.springframework.cloud</groupid> 
    <artifactid>spring-cloud-security</artifactid> 
</dependency> 
<!--oauth2.0-->
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
</dependency>

3.2 添加 bootstrap.yml 配置文件

security:
  oauth2:
   resource:
      userInfoUri: http://localhost:8901/auth/user

3.3 在主程序类上添加注解

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //断路器
@EnableResourceServer //表示受保护资源
public class Application {
    //注入一个过滤器,会拦截对服务的所有传入调用
    @Bean
    public Filter userContextFilter() {
        UserContextFilter userContextFilter = new UserContextFilter();
        return userContextFilter;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3.4 定义访问控制规则

在 config 包或 security 包下;

3.4.1 通过验证用户保护服务

//必须使用该注解,且需要扩展 ResourceServerConfigurerAdapter 类
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    //访问规则在 configure() 方法中定义,并且通过传入方法的 HttpSecurity 对象配置
    @Override
    public void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().anyRequest().authenticated();
    }
}

3.4.2 通过特定角色保护服务

@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception{
        http
        .authorizeRequests()
          .antMatchers(HttpMethod.DELETE, "/v1/xxxservices/**")  //运行部开发人员限制对受保护的 URL 和 HTTP DELETE 动词的调用
          .hasRole("ADMIN")  //允许访问的角色列表
          .anyRequest()
          .authenticated();
    }
}

4. 在上下游服务中传播 OAuth2 访问令牌

传播 OAuth2 访问令牌.png

4.1 配置服务网关的黑名单

在 Zuul 的 application.yml 的配置文件里;

4.2 修改上游服务业务代码

4.2.1 下游服务

4.2.2 在上游服务中公开 OAuth2RestTemplate 类

可以在主程序类上,也可以在主程序所在包及其子包里创建类;

4.2.3 在上游服务中用 OAuth2RestTemplate 来传播 OAuth2 访问令牌

@Component
public class OrganizationRestTemplateClient {
    //OAuth2RestTemplate 是标准的 RestTemplate 的增强式替代品,可处理 OAuth2 访问令牌
    @Autowired
    OAuth2RestTemplate restTemplate;

    public Organization getOrganization(String organizationId){
        //调用组织服务的方式与标准的 RestTemplate 完全相同
        ResponseEntity<Organization> restExchange =
                restTemplate.exchange(
                        "http://zuulserver:5555/api/organization/v1/organizations/{organizationId}",
                        HttpMethod.GET,
                        null, Organization.class, organizationId);
        return restExchange.getBody();
    }
}

最后

\color{blue}{\rm\small{新人制作,如有错误,欢迎指出,感激不尽!}}

\color{blue}{\rm\small{欢迎关注我,并与我交流!}}

\color{blue}{\rm\small{如需转载,请标注出处!}}

上一篇下一篇

猜你喜欢

热点阅读