# 基于 SAS 权限认证
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/02.%20%E5%90%8E%E7%AB%AF%E5%BC%80%E5%8F%91/04.%20%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6/01.%20%E5%9F%BA%E4%BA%8ESAS%E6%9D%83%E9%99%90%E8%AE%A4%E8%AF%81


# 基于 SAS 权限认证

注：Spring Authorization Server

## 1. 初始化

### 1.注入认证平台

 项目启动时通过加载 Bean`authorizationServerSecurityFilterChain` 将登录方式：后台、小程序、企微工作台、公众号 (客户端)、企业微信第三方、第三方依次注入到 `SecurityFilterChain` 中。并设置认证的请求，重定向到 login 页面行登录认证。(例：`oauth2/token`)

```java
@Bean  
@Order(1)  
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)  
        throws Exception {  
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);  
    // 注册自定义登录类型  
    http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)  
            //后台  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new SystemGrantAuthenticationConvert())  
                    .authenticationProvider(new SystemGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //openApi  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new OpenApiGrantAuthenticationConvert())  
                    .authenticationProvider(new OpenApiGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //小程序  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new MiniGrantAuthenticationConvert())  
                    .authenticationProvider(new MiniGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //企微工作台  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new WorkbenchGrantAuthenticationConvert())  
                    .authenticationProvider(new WorkbenchGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //客户端(公众号)  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new CustomerGrantAuthenticationConvert())  
                    .authenticationProvider(new CustomerGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //企业微信等第三方  
            .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new SocialGrantAuthenticationConvert())  
                    .authenticationProvider(new SocialGrantAuthenticationProvider(authorizationService, tokenGenerator())))  
            //开启OpenID Connect 1.0（其中oidc为OpenID Connect的缩写）。 访问 /.well-known/openid-configuration即可获取认证信息  
            .oidc(Customizer.withDefaults());  
    http  
            //将需要认证的请求，重定向到login页面行登录认证。  
            .exceptionHandling((exceptions) -> exceptions  
                    .defaultAuthenticationEntryPointFor(  
                            new LoginUrlAuthenticationEntryPoint(CommonConstant.LOGIN_ENDPOINT),  
                            //指定只有HTML类型的请求才会被重定向到登录页面  
                            new MediaTypeRequestMatcher(MediaType.TEXT_HTML)  
                    )  
            )  
            // 使用jwt处理接收到的access token  
            .oauth2ResourceServer(oauth2ResourceServer ->  
                    oauth2ResourceServer.jwt(Customizer.withDefaults()));  
    return http.build();  
}
```

### 2.注入放行接口并设置异常提醒类

项目启动时通过加载 Bean `defaultSecurityFilterChain`

将所有放行的接口注入到 `SecurityFilterChain` 中，并设置自定义认证异常提醒类 `JeecgAuthenticationException`

```java
@Bean  
@Order(2)  
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)  
        throws Exception {  
    http.authorizeHttpRequests((authorize) -> {  
                //从nacos获取需要放行的url配置文件(widiazine-security-permit-urls.json)  
                //设置所有请求都需要认证，未认证的请求都被重定向到login页面进行登录  
                securityPermitUrlsLoader.loadPermitUrlsByNacos().forEach(permitUrl -> authorize.requestMatchers(AntPathRequestMatcher.antMatcher(permitUrl)).permitAll());  
                //上述明确列出的URL模式之外的所有请求都必须经过认证  
                authorize.anyRequest().authenticated();  
            })  
            .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))  
            .cors(cors -> cors  
                    .configurationSource(req -> {  
                        CorsConfiguration config = new CorsConfiguration();  
                        config.applyPermitDefaultValues();  
                        config.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));  
                        return config;  
                    }))  
            .csrf(AbstractHttpConfigurer::disable)  
            .oauth2ResourceServer((oauth2) -> oauth2  
                    .jwt(Customizer.withDefaults())  
                    // 自定义认证异常  
                    .authenticationEntryPoint(new JeecgAuthenticationException()));  
    return http.build();  
}
```

### 3.设置 token 生成参数

 项目启动时通过加载 Bean`tokenGenerator` 设置 token 生成器

``` java
	/**  
 *配置token生成器  
 */  
@Bean  
OAuth2TokenGenerator<?> tokenGenerator() {  
    CustomerJwtTokenGenerator customerJwtTokenGenerator = new CustomerJwtTokenGenerator(new NimbusJwtEncoder(jwkSource()));  
    OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();  
    OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();  
    return new DelegatingOAuth2TokenGenerator(  
            customerJwtTokenGenerator, accessTokenGenerator, refreshTokenGenerator);  
}
```

### 4.配置 jwt 解析器

项目启动时通过加载 Bean`jwkSource、jwtDecoder` 创建 jwt 解析器

```java
/**  
 *配置 JWK，为JWT(id_token)提供加密密钥，用于加密/解密或签名/验签  
 * JWK详细见：https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key-41  
 */@Bean  
public JWKSource<SecurityContext> jwkSource() {  
    KeyPair keyPair = generateRsaKey();  
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
    RSAKey rsaKey = new RSAKey.Builder(publicKey)  
            .privateKey(privateKey)  
            // 重要！生产环境需要修改！  
            .keyID(keyId)  
            .build();  
    JWKSet jwkSet = new JWKSet(rsaKey);  
    return new ImmutableJWKSet<>(jwkSet);  
}

/**  
 *生成RSA密钥对，给上面jwkSource() 方法的提供密钥对  
 */  
private static KeyPair generateRsaKey() {  
    KeyPair keyPair;  
    try {  
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");  
  
        // 生产环境不应该设置secureRandom，seed如果被泄露，jwt容易被伪造  
        // 如果不设置secureRandom，会存在一个问题，当应用重启后，原有的token将会全部失效，因为重启的keyPair与之前已经不同  
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");  
        // 重要！生产环境需要修改！  
        secureRandom.setSeed(keyId.getBytes());  
        keyPairGenerator.initialize(2048, secureRandom);  
        keyPair = keyPairGenerator.generateKeyPair();  
    }  
    catch (Exception ex) {  
        throw new IllegalStateException(ex);  
    }  
    return keyPair;  
}
```

## 2.登录

### 1.后台

1. 前端通过访问接口 `oauth2/token`，并携带参数 `grant_type(授权平台)、checkKey(验证码检查key)、captcha(验证码)、username(用户名)、password(密码)` 向后端请求。
2. 后端收到前端请求后，根据参数 `grant_type` 传入的值，依次按初始化时绑定的自定义登录类型去找到对应的授权平台，并初步校验账号密码是否为空，将传入的参数转换为 `Authentication` 所需要的参数格式
3. 当满足第二步的条件后，根据转换后的参数，检查用户基础信息、状态等。将不满足条件的用户给出对应的提示，满足的用户返回对应信息及 token

### 2.小程序

1. 小程序端通过访问 `oauth2/token`,并携带参数 `grant_type(授权平台)、platCode(平台code)、code(微信code)、channel(渠道)` 向后端请求。
2. 后端收到前端请求后，根据参数 `grant_type` 传入的值，依次按初始化时绑定的自定义登录类型去找到对应的授权平台，将传入的参数转换为 `Authentication` 所需要的参数格式
3. 当满足第二步的条件后,根据传入的参数向 mini 包做 `wxlogin` 动作，并返回用户信息及 token 相关

**公众号、企微、第三方同理小程序，只不过就是第三步中查询用户信息的接口不一样**

> [!info] 注意点
> 项目启动时会加载一个表 `oauth2_registered_client` 存放客户端认证信息，里面存放了客户端信息及 token 相关配置信息，现默认在 public 模式下。路由只在 system 中设置 oauth2
