diff --git a/README.md b/README.md index 16770e4..54d4877 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ |---|:---:|---| | Auto-configuration | Declared in source | Registers security-yiban beans automatically | | Property Binding | Declared in source | Binds `spring.security.yiban.authc.*` to `SecurityYibanAuthcProperties` | -| `Authorize` bean | Declared in source | Auto-registered via SecurityYibanAutoConfiguration | +| `YibanOAuthClient` bean | Declared in source | Auto-registered via SecurityYibanAutoConfiguration | ## 3. Requirements and Compatibility @@ -60,10 +60,7 @@ For Boot 2.3 applications using the Boot parent, set `spring-framework.version` snapshot build `2.7.x.20260630-20261029.080305-2`, which is verified with Boot 2.3.12 and JDK 8 in this starter. Use the Easy4J Maven snapshot settings when building or consuming it. -The build checks the SHA-256 of `YBOpenApi.jar` in the repository's `YBApi_sdk_java.zip` -and includes the SDK classes from the 2015-08-20 archive. It supplies a replacement HTTP transport -with the JVM's certificate trust and hostname verification, bounded timeouts and no redirects. -The starter no longer resolves `cn.yiban.open:java-sdk:1.6.0`. +The starter implements the OAuth contract from the official Yiban Java example (2.26.1103) with its existing Apache HttpClient. It uses the JVM trust store and hostname verification and disables redirects for API requests. ## 4. Auto-configuration @@ -71,29 +68,17 @@ The starter auto-configures the following beans: | Bean | Condition | Missing Behavior | |---|---|---| -| `Authorize` | classpath + property | not created | +| `YibanOAuthClient` | classpath + property | not created | | `SecurityContextLogoutHandler` | classpath + property | not created | | `YibanMatchedAuthenticationEntryPoint` | classpath + property | not created | | `YibanMatchedAuthenticationFailureHandler` | classpath + property | not created | | `YibanAuthenticationProvider` | classpath + property | not created | -The source declares configuration classes, while the Boot 2.3 discovery file -`META-INF/spring.factories` is absent. Verify configuration discovery and the -live Yiban sign-in flow before using this branch. +Boot 2.3 discovers these configurations through `META-INF/spring.factories`. The registered callback must route to `/login/yiban` by default, or to the configured `spring.security.yiban.authc.login-url`. ## 5. Dependencies -The build requires two artifacts that are currently unresolved: - -- `cn.yiban.open:java-sdk:1.6.0` for Yiban authorization and user APIs. -- `io.github.easy4j:security-biz-spring-boot-starter:1.0.9-SNAPSHOT` for shared Spring Security components. - -The [official Yiban Java download](https://open.yiban.cn/wiki/download/oauth_java.7z) -contains a Servlet authorization example. The archive does not contain the Maven -SDK JAR. Resolve both artifacts from a trusted repository and verify the Java 8 -build and Yiban integration before using any release coordinates. - -The historical Security Biz `1.0.9` source used earlier organization coordinates. Independent resolution from the configured Aliyun repository found neither `1.0.9-SNAPSHOT` nor the Boot 2.3 maintenance snapshot `2.3.x.20260630-SNAPSHOT` under the Easy4J coordinates. Moving to the maintained line also requires verification of Spring Security and authentication error compatibility. +Use the starter with the Easy4J Security Biz dependency available from the snapshot repository. Provide a `UserDetailsServiceAdapter` bean to map verified Yiban credentials to a local account. ## 6. Enable Yiban configuration @@ -104,6 +89,10 @@ spring: security: yiban: enabled: true + authc: + app-key: ${YIBAN_APP_KEY} + app-secret: ${YIBAN_APP_SECRET} + callback: https://app.example.com/login/yiban ``` ## 7. Configuration Reference @@ -119,6 +108,8 @@ spring: | `spring.security.yiban.enabled` | boolean | `false` | No | Enable the starter | No | +Authorization uses a one-time session state. Check the [OAuth migration notes](docs/reviews/pr-2-current-oauth.md) when updating existing Yiban integrations. + ## 8. Version Lines and Compatibility | Branch | JDK | Spring Boot | Component Version | Status | diff --git a/README.zh-CN.md b/README.zh-CN.md index 8bb4505..0ab677b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -45,7 +45,7 @@ |---|:---:|---| | 自动装配 | 源码已声明 | 自动注册 security-yiban 相关 Bean | | 属性绑定 | 源码已声明 | 绑定 `spring.security.yiban.authc.*` 到 `SecurityYibanAuthcProperties` | -| `Authorize` Bean | 源码已声明 | 通过 SecurityYibanAutoConfiguration 自动注册 | +| `YibanOAuthClient` Bean | 源码已声明 | 通过 SecurityYibanAutoConfiguration 自动注册 | ## 3. 运行要求与兼容性 @@ -60,9 +60,7 @@ 快照构建 `2.7.x.20260630-20261029.080305-2`,本 Starter 在 JDK 8 与 Boot 2.3.12 上验证其运行兼容性。 构建和消费该构件时需配置 Easy4J Maven 快照仓库。 -构建校验仓库内 `YBApi_sdk_java.zip` 中 `YBOpenApi.jar` 的 SHA-256,再打包 2015-08-20 -归档中的 SDK 类。HTTP 传输使用 JVM 证书信任库和主机名校验,设定超时并禁用重定向。 -Starter 不再解析 `cn.yiban.open:java-sdk:1.6.0`。 +Starter 使用现有 Apache HttpClient 实现易班 Java 官方示例 2.26.1103 的 OAuth 协议。接口请求使用 JVM 信任库和主机名校验,并禁用重定向。 ## 4. 自动装配 @@ -70,24 +68,17 @@ Starter 自动装配以下 Bean: | Bean | 条件 | 缺失时行为 | |---|---|---| -| `Authorize` | classpath + property | 不创建 | +| `YibanOAuthClient` | classpath + property | 不创建 | | `SecurityContextLogoutHandler` | classpath + property | 不创建 | | `YibanMatchedAuthenticationEntryPoint` | classpath + property | 不创建 | | `YibanMatchedAuthenticationFailureHandler` | classpath + property | 不创建 | | `YibanAuthenticationProvider` | classpath + property | 不创建 | -当前源码包含配置类,但没有 Boot 2.3 自动发现使用的 `META-INF/spring.factories`。自动发现及真实易班登录流程仍待验证。 +Boot 2.3 通过 `META-INF/spring.factories` 发现这些自动配置。注册回调默认应指向 `/login/yiban`,也可使用应用配置的 `spring.security.yiban.authc.login-url`。 ## 5. 引入依赖 -本分支构建仍需解析以下依赖: - -- `cn.yiban.open:java-sdk:1.6.0`,易班授权及用户接口。 -- `io.github.easy4j:security-biz-spring-boot-starter:1.0.9-SNAPSHOT`,通用 Spring Security 组件。 - -[易班官方下载的 Java 压缩包](https://open.yiban.cn/wiki/download/oauth_java.7z)包含 Servlet 授权示例,未提供上述 Maven SDK JAR。需先从可信来源解析这两个 Maven 制品,并完成 Java 8 构建和联调,再验证可用的发布坐标。 - -Security Biz 的历史 `1.0.9` 源码使用旧组织坐标。对阿里云私服的独立解析显示,Easy4J 坐标下的 `1.0.9-SNAPSHOT` 和 Boot 2.3 维护版 `2.3.x.20260630-SNAPSHOT` 均未解析到。切换到维护版还需验证 Spring Security 版本及异常响应兼容性。 +使用 Starter 时需能从 Easy4J 快照仓库解析 Security Biz,应用需提供 `UserDetailsServiceAdapter` Bean,把已验证的易班凭据映射到本地账号。 ## 6. 启用配置 @@ -98,6 +89,10 @@ spring: security: yiban: enabled: true + authc: + app-key: ${YIBAN_APP_KEY} + app-secret: ${YIBAN_APP_SECRET} + callback: https://app.example.com/login/yiban ``` ## 7. 配置参考 @@ -113,6 +108,8 @@ spring: | `spring.security.yiban.enabled` | boolean | `false` | 否 | 是否启用 Starter | 否 | +授权流程使用会话内的一次性状态。升级已接入易班的应用时,请核对[迁移说明](docs/reviews/pr-2-current-oauth.md)。 + ## 8. 版本线与兼容性 | 分支 | JDK | Spring Boot | 组件版本 | 状态 | diff --git a/docs/reviews/pr-2-current-oauth.md b/docs/reviews/pr-2-current-oauth.md new file mode 100644 index 0000000..b2a5d7f --- /dev/null +++ b/docs/reviews/pr-2-current-oauth.md @@ -0,0 +1,15 @@ +# 易班 PR #2 的 OAuth 迁移 + +官网发布的 Java SDK 2.26.1103 提供 JDK 11 与 Jakarta Servlet 示例源码。本 Starter 保留 JDK 8 与 Spring Boot 2.3,复用已有 Apache HttpClient 实现该协议。[官方 Java SDK 下载](https://o.yiban.cn/wiki/index.php?page=SDK%E4%B8%8B%E8%BD%BD) + +| 步骤 | 接口 | 验收 | +| --- | --- | --- | +| 发起授权 | `GET https://oauth.yiban.cn/code/authorize` | 发送应用 ID、注册回调和会话级随机 state | +| 换取令牌 | `POST https://oauth.yiban.cn/token/info` | 校验并消耗 state 后,以 UTF-8 表单发送 code、应用 ID、密钥与注册回调 | +| 读取用户 | `GET https://openapi.yiban.cn/user/me` | 成功响应须包含 `info.yb_userid`,再由应用的 `UserDetailsServiceAdapter` 完成本地认证 | + +用户接口遵循公开 API 指定的 `access_token` 查询参数。学校实名验证属于易班独立接口,应用应根据自身业务规则选择。[易班 user/me 文档](https://o.yiban.cn/wiki/index.php?page=user/me) + +原 `yibanAuthorize` Bean 现在返回 `YibanOAuthClient`。直接引用旧 SDK 类型的代码应迁移到新客户端。已有 `state` 属性可继续绑定,实际授权使用每次生成的一次性值。新版授权接口移除了 `display` 参数。若配置 `redirect_uri`,该值优先于 `callback`,授权和换令牌请求使用同一地址。应用需在易班开放平台注册该地址,并将它路由到 Starter 的登录入口。 + +集成测试使用本机 HTTP 模拟易班,覆盖自动装配、浏览器授权跳转、回调、一次性状态校验、用户映射以及失败响应。真实平台联调需要已注册的应用、密钥和可用回调地址。 diff --git a/pom.xml b/pom.xml index f49bd43..48a958a 100644 --- a/pom.xml +++ b/pom.xml @@ -247,39 +247,6 @@ - - org.apache.maven.plugins - maven-antrun-plugin - 3.1.0 - - - verify-and-unpack-yiban-sdk - generate-resources - run - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/java/cn/yiban/util/HTTPSimple.java b/src/main/java/cn/yiban/util/HTTPSimple.java deleted file mode 100644 index 0c8a690..0000000 --- a/src/main/java/cn/yiban/util/HTTPSimple.java +++ /dev/null @@ -1,62 +0,0 @@ -package cn.yiban.util; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Objects; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; - -/** 保留旧版易班 SDK 的静态传输入口,使用 JVM 默认信任库和主机名验证。 */ -@Slf4j -public final class HTTPSimple { - - private static final RequestConfig TIMEOUTS = RequestConfig.custom() - .setConnectTimeout(5000) - .setSocketTimeout(10000) - .build(); - - private HTTPSimple() { - } - - /** 返回易班 GET 响应正文。 */ - public static String GET(String url) { - return execute(new HttpGet(url)); - } - - /** 以 UTF-8 表单发送易班 POST 请求。 */ - public static String POST(String url, List parameters) { - HttpPost request = new HttpPost(url); - request.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8)); - return execute(request); - } - - private static String execute(HttpUriRequest request) { - try (CloseableHttpClient client = HttpClients.custom() - .disableRedirectHandling() - .setDefaultRequestConfig(TIMEOUTS) - .build(); - CloseableHttpResponse response = client.execute(request)) { - int status = response.getStatusLine().getStatusCode(); - if (status >= 300 && status < 400) { - log.warn("Yiban API returned a redirect, status={}", status); - return ""; - } - HttpEntity entity = response.getEntity(); - return Objects.isNull(entity) ? "" : EntityUtils.toString(entity, StandardCharsets.UTF_8); - } catch (IOException ex) { - log.warn("Yiban API request failed, errorType={}", ex.getClass().getSimpleName()); - return ""; - } - } -} diff --git a/src/main/java/org/springframework/security/boot/SecurityYibanAuthcProperties.java b/src/main/java/org/springframework/security/boot/SecurityYibanAuthcProperties.java index aa8bb8c..f2a1ed6 100644 --- a/src/main/java/org/springframework/security/boot/SecurityYibanAuthcProperties.java +++ b/src/main/java/org/springframework/security/boot/SecurityYibanAuthcProperties.java @@ -26,7 +26,6 @@ import org.springframework.security.boot.yiban.authentication.YibanAuthorizationProcessingFilter; import org.springframework.security.core.Authentication; -import cn.yiban.open.Authorize; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -40,6 +39,10 @@ public class SecurityYibanAuthcProperties extends SecurityAuthcProperties { public static final String PREFIX = "spring.security.yiban.authc"; + public SecurityYibanAuthcProperties() { + setPathPattern(YibanAuthorizationProcessingFilter.AUTHORIZATION_PATH); + } + /** * 接入应用 APPID */ @@ -47,6 +50,7 @@ public class SecurityYibanAuthcProperties extends SecurityAuthcProperties { /** * 接入应用的 AppSecret */ + @ToString.Exclude private String appSecret; private String callback; @@ -64,7 +68,6 @@ public class SecurityYibanAuthcProperties extends SecurityAuthcProperties { /** 异常页面:认证失败时的跳转路径 */ private String failureUrl = "/error"; - private Authorize.DISPLAY_TAG_T display = Authorize.DISPLAY_TAG_T.WEB; private String authorizationParamName = YibanAuthorizationProcessingFilter.AUTHORIZATION_PARAM; diff --git a/src/main/java/org/springframework/security/boot/SecurityYibanAutoConfiguration.java b/src/main/java/org/springframework/security/boot/SecurityYibanAutoConfiguration.java index aefefd0..3c2c50a 100644 --- a/src/main/java/org/springframework/security/boot/SecurityYibanAutoConfiguration.java +++ b/src/main/java/org/springframework/security/boot/SecurityYibanAutoConfiguration.java @@ -10,23 +10,28 @@ import org.springframework.security.boot.yiban.authentication.YibanAuthenticationProvider; import org.springframework.security.boot.yiban.authentication.YibanMatchedAuthenticationEntryPoint; import org.springframework.security.boot.yiban.authentication.YibanMatchedAuthenticationFailureHandler; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; -import cn.yiban.open.Authorize; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; +import org.springframework.util.StringUtils; @Configuration @AutoConfigureBefore(SecurityBizAutoConfiguration.class) @ConditionalOnProperty(prefix = SecurityYibanProperties.PREFIX, value = "enabled", havingValue = "true") -@EnableConfigurationProperties({ SecurityYibanProperties.class }) +@EnableConfigurationProperties({ SecurityYibanProperties.class, SecurityYibanAuthcProperties.class }) public class SecurityYibanAutoConfiguration { /** - * 在程序文件中导入并使用AppID与AppSecret来初始化cn.yiban.open.Authorize + * 创建使用当前易班 OAuth 接口的客户端。 */ @Bean - public Authorize yibanAuthorize(SecurityYibanAuthcProperties authcProperties) { - return new Authorize(authcProperties.getAppKey(), authcProperties.getAppSecret()); + @ConditionalOnMissingBean(YibanOAuthClient.class) + public YibanOAuthClient yibanAuthorize(SecurityYibanAuthcProperties authcProperties) { + String redirectUri = authcProperties.getRedirect_uri(); + if (!StringUtils.hasText(redirectUri)) { + redirectUri = authcProperties.getCallback(); + } + return new YibanOAuthClient(authcProperties.getAppKey(), authcProperties.getAppSecret(), redirectUri); } @@ -54,8 +59,8 @@ public YibanMatchedAuthenticationFailureHandler yibanMatchedAuthenticationFailur @Bean public YibanAuthenticationProvider yibanAuthenticationProvider(UserDetailsServiceAdapter userDetailsService, - PasswordEncoder passwordEncoder) { - return new YibanAuthenticationProvider(userDetailsService); + YibanOAuthClient yibanAuthorize) { + return new YibanAuthenticationProvider(userDetailsService, yibanAuthorize); } } diff --git a/src/main/java/org/springframework/security/boot/SecurityYibanFilterConfiguration.java b/src/main/java/org/springframework/security/boot/SecurityYibanFilterConfiguration.java index b748a88..81c3623 100644 --- a/src/main/java/org/springframework/security/boot/SecurityYibanFilterConfiguration.java +++ b/src/main/java/org/springframework/security/boot/SecurityYibanFilterConfiguration.java @@ -1,16 +1,19 @@ package org.springframework.security.boot; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; import org.springframework.beans.factory.ObjectProvider; import org.springframework.extension.web.servlet.i18n.LocaleContextFilter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Bean; +import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.boot.biz.authentication.AuthenticationListener; import org.springframework.security.boot.biz.authentication.nested.MatchedAuthenticationEntryPoint; @@ -23,17 +26,21 @@ import org.springframework.security.boot.yiban.authentication.YibanPreAuthenticatedProcessingFilter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.OrRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -import cn.yiban.open.Authorize; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; @Configuration -@AutoConfigureBefore(name = { - "org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration" +@AutoConfigureAfter(name = { + "org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration" }) @ConditionalOnWebApplication @ConditionalOnProperty(prefix = SecurityYibanProperties.PREFIX, value = "enabled", havingValue = "true") @@ -45,7 +52,7 @@ public class SecurityYibanFilterConfiguration { static class YibanWebSecurityConfigurerAdapter extends WebSecurityBizConfigurerAdapter { private final SecurityYibanAuthcProperties authcProperties; - private final Authorize yibanAuthorize; + private final YibanOAuthClient yibanAuthorize; private final LocaleContextFilter localeContextFilter; private final AuthenticationEntryPoint authenticationEntryPoint; @@ -60,7 +67,7 @@ public YibanWebSecurityConfigurerAdapter( SecuritySessionMgtProperties sessionMgtProperties, SecurityYibanAuthcProperties authcProperties, - ObjectProvider authorizeProvider, + ObjectProvider authorizeProvider, ObjectProvider localeContextProvider, ObjectProvider authenticationProvider, ObjectProvider authenticationListenerProvider, @@ -88,17 +95,14 @@ public YibanWebSecurityConfigurerAdapter( public YibanPreAuthenticatedProcessingFilter preAuthenticatedProcessingFilter() throws Exception { - YibanPreAuthenticatedProcessingFilter authcFilter = new YibanPreAuthenticatedProcessingFilter( yibanAuthorize, - authcProperties.getCallback(), - authcProperties.getState(), - authcProperties.getDisplay()); - - return authcFilter; + return new YibanPreAuthenticatedProcessingFilter(yibanAuthorize, + authcProperties.getLoginUrl(), authcProperties.getAuthorizationParamName()); } public YibanAuthorizationProcessingFilter authenticationProcessingFilter() throws Exception { YibanAuthorizationProcessingFilter authcFilter = new YibanAuthorizationProcessingFilter(yibanAuthorize); + authcFilter.setAuthorizationParamName(authcProperties.getAuthorizationParamName()); authcFilter.setAllowSessionCreation(getSessionMgtProperties().isAllowSessionCreation()); authcFilter.setAuthenticationFailureHandler(authenticationFailureHandler); @@ -109,22 +113,43 @@ public YibanAuthorizationProcessingFilter authenticationProcessingFilter() throw if (StringUtils.hasText(authcProperties.getLoginUrl())) { authcFilter.setFilterProcessesUrl(authcProperties.getLoginUrl()); } - authcFilter.setRememberMeServices(rememberMeServices); - authcFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); + if (Objects.nonNull(rememberMeServices)) { + authcFilter.setRememberMeServices(rememberMeServices); + } + if (Objects.nonNull(sessionAuthenticationStrategy)) { + authcFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); + } return authcFilter; } + @Bean + @Order(100) + WebSecurityConfigurerAdapter yibanSecurityConfigurer() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + YibanWebSecurityConfigurerAdapter.this.configure(http); + } + }; + } + @Override protected void configure(HttpSecurity http) throws Exception { + if (Objects.nonNull(localeContextFilter)) { + http.addFilterBefore(localeContextFilter, UsernamePasswordAuthenticationFilter.class); + } - http.antMatcher(authcProperties.getPathPattern()) + RequestMatcher login = new AntPathRequestMatcher(authcProperties.getLoginUrl()); + String pathPattern = authcProperties.getPathPattern(); + RequestMatcher scope = StringUtils.hasText(pathPattern) + ? new OrRequestMatcher(login, new AntPathRequestMatcher(pathPattern)) : login; + http.requestMatcher(scope) .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .httpBasic() .disable() - .addFilterBefore(localeContextFilter, UsernamePasswordAuthenticationFilter.class) .addFilterBefore(preAuthenticatedProcessingFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(authenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class); diff --git a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthenticationProvider.java b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthenticationProvider.java index 2cf7abf..da91ab0 100644 --- a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthenticationProvider.java +++ b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthenticationProvider.java @@ -2,9 +2,9 @@ import java.util.Locale; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; +import org.springframework.util.StringUtils; +import java.util.Objects; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; @@ -22,23 +22,23 @@ import com.alibaba.fastjson.JSONObject; -import cn.yiban.open.common.User; public class YibanAuthenticationProvider implements AuthenticationProvider { protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final YibanOAuthClient yibanOAuthClient; private final UserDetailsServiceAdapter userDetailsService; private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker(); - public YibanAuthenticationProvider(final UserDetailsServiceAdapter userDetailsService) { + public YibanAuthenticationProvider(UserDetailsServiceAdapter userDetailsService, YibanOAuthClient yibanOAuthClient) { this.userDetailsService = userDetailsService; + this.yibanOAuthClient = yibanOAuthClient; } /** * *

完成匹配Token的认证,这里返回的对象最终会通过:SecurityContextHolder.getContext().setAuthentication(authResult); 放置在上下文中

- * @author :wandl + * @author Loong Wan * @param authentication {@link YibanAuthenticationToken IdentityCodeAuthenticationToken} 对象 * @return 认证结果{@link Authentication}对象 * @throws AuthenticationException 认证失败会抛出异常 @@ -48,57 +48,22 @@ public Authentication authenticate(Authentication authentication) throws Authent Assert.notNull(authentication, "No authentication data provided"); - if (logger.isDebugEnabled()) { - logger.debug("Processing authentication request : " + authentication); - } - - String token = (String) authentication.getPrincipal(); - - if (!StringUtils.isBlank(token)) { - logger.debug("No principal found in request."); - throw new BadCredentialsException("No principal found in request."); - } - - /** - * 获取当前用户实名信息 - * https://open.yiban.cn/wiki/index.php?page=user/real_me - */ - JSONObject realme = JSONObject.parseObject(new User(token).realme()); - // 判断响应状态 - if(StringUtils.equalsIgnoreCase(realme.getString("status"), "error")) { - // 异常内容 - JSONObject info = realme.getJSONObject("info"); - if (LocaleContextHolder.getLocale().getLanguage().equals(Locale.CHINESE.getLanguage())) { - throw new AuthenticationYibanServerException(info.getString("code"), info.getString("msgCN")); - } - throw new AuthenticationYibanServerException(info.getString("code"), info.getString("msgEN")); - } - /** - { - "status":"success", - "info":{ - "yb_userid":"易班用户id", - "yb_username":"用户名", - "yb_usernick":"用户昵称", - "yb_sex":"性别", - "yb_money":"持有网薪", - "yb_exp":"经验值", - "yb_userhead":"用户头像", - "yb_schoolid":"所在学校id", - "yb_schoolname":"所在学校名称", - "yb_realname":"真实姓名", - "yb_birthday":"生日", - "yb_studentid":"学校首选认证类型编号",//如对认证信息的类型敏感,该字段建议使用user/verify_me接口代替 - "yb_identity":"用户身份"//枚举,学生、老师、辅导员、未认证 - } - } - */ - JSONObject info = realme.getJSONObject("info"); - - - info.getString("yb_userid"); - - + Object principal = authentication.getPrincipal(); + if (!(principal instanceof String) || !StringUtils.hasText((String) principal)) { + throw new BadCredentialsException("Missing Yiban access token"); + } + JSONObject profile = yibanOAuthClient.userInfo((String) principal); + JSONObject info = profile.getJSONObject("info"); + if ("error".equalsIgnoreCase(profile.getString("status")) && Objects.nonNull(info)) { + String messageKey = Locale.CHINESE.getLanguage().equals(LocaleContextHolder.getLocale().getLanguage()) + ? "msgCN" : "msgEN"; + throw new AuthenticationYibanServerException(info.getString("code"), info.getString(messageKey)); + } + if (!"success".equalsIgnoreCase(profile.getString("status")) || Objects.isNull(info) + || !StringUtils.hasText(info.getString("yb_userid"))) { + throw new BadCredentialsException("Missing Yiban user identity"); + } + UserDetails ud = getUserDetailsService().loadUserDetails(authentication); // User Status Check diff --git a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthorizationProcessingFilter.java b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthorizationProcessingFilter.java index 2f356a2..cd790db 100644 --- a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthorizationProcessingFilter.java +++ b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanAuthorizationProcessingFilter.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; import javax.servlet.FilterChain; @@ -31,7 +32,6 @@ import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.boot.biz.authentication.PostOnlyAuthenticationProcessingFilter; import org.springframework.security.boot.biz.exception.AuthenticationTokenNotFoundException; -import org.springframework.security.boot.utils.StringUtils; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; @@ -41,12 +41,14 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.CollectionUtils; -import cn.yiban.open.Authorize; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; +import org.springframework.security.boot.yiban.client.YibanAuthorizationState; +import org.springframework.util.StringUtils; /** * Jwt授权 (authorization)过滤器 * - * @author : hiwepy + * @author Loong Wan */ public class YibanAuthorizationProcessingFilter extends PostOnlyAuthenticationProcessingFilter { @@ -56,21 +58,27 @@ public class YibanAuthorizationProcessingFilter extends PostOnlyAuthenticationPr private List ignoreRequestMatchers; private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy(); - private final Authorize authorize; + private final YibanOAuthClient authorize; - public YibanAuthorizationProcessingFilter(Authorize authorize) { + public YibanAuthorizationProcessingFilter(YibanOAuthClient authorize) { super(new AntPathRequestMatcher(AUTHORIZATION_PATH)); this.authorize = authorize; + setPostOnly(false); } - public YibanAuthorizationProcessingFilter(Authorize authorize, List ignorePatterns) { + public YibanAuthorizationProcessingFilter(YibanOAuthClient authorize, List ignorePatterns) { super(new AntPathRequestMatcher(AUTHORIZATION_PATH)); this.setIgnoreRequestMatcher(ignorePatterns); this.authorize = authorize; + setPostOnly(false); } @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + if (Objects.isNull(request.getParameter(getAuthorizationParamName())) + && Objects.isNull(request.getParameter("state")) && Objects.isNull(request.getParameter("error"))) { + return false; + } // 忽略部分请求 if(!CollectionUtils.isEmpty(ignoreRequestMatchers)) { for (RequestMatcher requestMatcher : ignoreRequestMatchers) { @@ -143,20 +151,13 @@ public void setSessionAuthenticationStrategy( public Authentication doAttemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { - String code = request.getParameter(getAuthorizationParamName());; - - if (code == null) { - code = ""; + YibanAuthorizationState.consume(request); + String code = request.getParameter(getAuthorizationParamName()); + if (!StringUtils.hasText(code)) { + throw new AuthenticationTokenNotFoundException("Missing Yiban authorization code"); } + String token = authorize.exchangeCode(code.trim()); - code = code.trim(); - - String token = authorize.querytoken(code, ""); - - if(!StringUtils.hasText(token)) { - throw new AuthenticationTokenNotFoundException("yiban token not provided"); - } - AbstractAuthenticationToken authRequest = new YibanAuthenticationToken(token); // Allow subclasses to set the "details" property diff --git a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanPreAuthenticatedProcessingFilter.java b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanPreAuthenticatedProcessingFilter.java index c3c5b6d..1885d06 100644 --- a/src/main/java/org/springframework/security/boot/yiban/authentication/YibanPreAuthenticatedProcessingFilter.java +++ b/src/main/java/org/springframework/security/boot/yiban/authentication/YibanPreAuthenticatedProcessingFilter.java @@ -1,21 +1,7 @@ -/* - * Copyright (c) 2018, hiwepy (https://github.com/hiwepy). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ package org.springframework.security.boot.yiban.authentication; import java.io.IOException; +import java.util.Objects; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -24,45 +10,45 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.security.boot.utils.WebUtils; +import org.springframework.security.boot.yiban.client.YibanAuthorizationState; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; -import cn.yiban.open.Authorize; -import cn.yiban.open.Authorize.DISPLAY_TAG_T; - +/** 仅在授权入口发起易班授权。回调由登录处理过滤器处理。 */ public class YibanPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { - private final Authorize authorize; - private final String redirect_uri; - private final String state; - private final Authorize.DISPLAY_TAG_T display; - - public YibanPreAuthenticatedProcessingFilter(Authorize authorize, String redirect_uri, String state, - DISPLAY_TAG_T display) { - super(); - this.authorize = authorize; - this.redirect_uri = redirect_uri; - this.state = state; - this.display = display; - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - - String url = authorize.forwardurl(redirect_uri, state, display); - - // 其中backurl为应用的回调地址,授权服务器授权后会重定向到这个地址。 "QUERY" 为一状态参数,授权服务器原样返回。Authorize.DISPLAY_TAG_T.WEB 标识请求验证的客户端类型。 - WebUtils.getNativeResponse(response, HttpServletResponse.class).sendRedirect(url); - - } - - protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) { - return "N/A"; - } - - protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) { - return "N/A"; - } - -} \ No newline at end of file + private final YibanOAuthClient authorize; + private final RequestMatcher initiationRequest; + private final String codeParameter; + + public YibanPreAuthenticatedProcessingFilter(YibanOAuthClient authorize, String loginUrl, String codeParameter) { + this.authorize = authorize; + this.initiationRequest = new AntPathRequestMatcher(loginUrl, "GET"); + this.codeParameter = codeParameter; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest http = (HttpServletRequest) request; + if (!initiationRequest.matches(http) || Objects.nonNull(http.getParameter(codeParameter)) + || Objects.nonNull(http.getParameter("state")) || Objects.nonNull(http.getParameter("error"))) { + chain.doFilter(request, response); + return; + } + String state = YibanAuthorizationState.issue(http); + ((HttpServletResponse) response).sendRedirect(authorize.authorizationUri(state).toASCIIString()); + } + + @Override + protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { + return "N/A"; + } + + @Override + protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { + return "N/A"; + } +} diff --git a/src/main/java/org/springframework/security/boot/yiban/client/YibanAuthorizationState.java b/src/main/java/org/springframework/security/boot/yiban/client/YibanAuthorizationState.java new file mode 100644 index 0000000..aaf30d1 --- /dev/null +++ b/src/main/java/org/springframework/security/boot/yiban/client/YibanAuthorizationState.java @@ -0,0 +1,47 @@ +package org.springframework.security.boot.yiban.client; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Objects; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.util.StringUtils; +import org.springframework.web.util.WebUtils; + +/** 管理与发起会话关联的一次性易班授权状态。 */ +public final class YibanAuthorizationState { + + private static final String KEY = YibanAuthorizationState.class.getName(); + + private YibanAuthorizationState() { + } + + public static String issue(HttpServletRequest request) { + String state = UUID.randomUUID().toString(); + HttpSession session = request.getSession(); + synchronized (WebUtils.getSessionMutex(session)) { + session.setAttribute(KEY, state); + } + return state; + } + + public static void consume(HttpServletRequest request) { + String received = request.getParameter("state"); + HttpSession session = request.getSession(false); + if (Objects.isNull(session) || !StringUtils.hasText(received)) { + throw new BadCredentialsException("Missing Yiban authorization state"); + } + synchronized (WebUtils.getSessionMutex(session)) { + Object value = session.getAttribute(KEY); + if (!(value instanceof String) || !MessageDigest.isEqual( + ((String) value).getBytes(StandardCharsets.UTF_8), received.getBytes(StandardCharsets.UTF_8))) { + throw new BadCredentialsException("Invalid Yiban authorization state"); + } + session.removeAttribute(KEY); + } + } +} diff --git a/src/main/java/org/springframework/security/boot/yiban/client/YibanOAuthClient.java b/src/main/java/org/springframework/security/boot/yiban/client/YibanOAuthClient.java new file mode 100644 index 0000000..0640ee1 --- /dev/null +++ b/src/main/java/org/springframework/security/boot/yiban/client/YibanOAuthClient.java @@ -0,0 +1,135 @@ +package org.springframework.security.boot.yiban.client; + +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** 访问官方易班 OAuth 授权、换令牌和用户信息接口。 */ +public final class YibanOAuthClient implements Closeable { + + private static final URI AUTHORIZATION = URI.create("https://oauth.yiban.cn/code/authorize"); + private static final URI TOKEN = URI.create("https://oauth.yiban.cn/token/info"); + private static final URI USER = URI.create("https://openapi.yiban.cn/user/me"); + + private final CloseableHttpClient http; + private final URI authorizationEndpoint; + private final URI tokenEndpoint; + private final URI userEndpoint; + private final String appKey; + private final String appSecret; + private final String redirectUri; + + public YibanOAuthClient(String appKey, String appSecret, String redirectUri) { + this(appKey, appSecret, redirectUri, AUTHORIZATION, TOKEN, USER); + } + + YibanOAuthClient(String appKey, String appSecret, String redirectUri, + URI authorizationEndpoint, URI tokenEndpoint, URI userEndpoint) { + Assert.hasText(appKey, "Yiban app key must be configured"); + Assert.hasText(appSecret, "Yiban app secret must be configured"); + Assert.hasText(redirectUri, "Yiban redirect URI must be configured"); + URI callback = URI.create(redirectUri); + Assert.isTrue(("https".equalsIgnoreCase(callback.getScheme()) || "http".equalsIgnoreCase(callback.getScheme())) + && Objects.nonNull(callback.getHost()) && Objects.isNull(callback.getFragment()) + && Objects.isNull(callback.getUserInfo()), "Invalid Yiban redirect URI"); + this.appKey = appKey; + this.appSecret = appSecret; + this.redirectUri = redirectUri; + this.authorizationEndpoint = authorizationEndpoint; + this.tokenEndpoint = tokenEndpoint; + this.userEndpoint = userEndpoint; + this.http = HttpClients.custom() + .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(5000) + .setConnectionRequestTimeout(5000).setSocketTimeout(10000).build()) + .disableRedirectHandling() + .disableAutomaticRetries() + .build(); + } + + /** 生成带一次性状态的授权地址。 */ + public URI authorizationUri(String state) { + Assert.hasText(state, "Yiban authorization state is required"); + return build(new URIBuilder(authorizationEndpoint) + .addParameter("client_id", appKey) + .addParameter("redirect_uri", redirectUri) + .addParameter("state", state)); + } + + /** 使用与授权请求相同的回调地址换取令牌。 */ + public String exchangeCode(String code) { + Assert.hasText(code, "Yiban authorization code is required"); + HttpPost request = new HttpPost(tokenEndpoint); + request.setEntity(new UrlEncodedFormEntity(Arrays.asList( + new BasicNameValuePair("code", code), + new BasicNameValuePair("client_secret", appSecret), + new BasicNameValuePair("client_id", appKey), + new BasicNameValuePair("redirect_uri", redirectUri)), StandardCharsets.UTF_8)); + String token = execute(request).getString("access_token"); + if (!StringUtils.hasText(token)) { + throw new AuthenticationServiceException("Yiban did not return an access token"); + } + return token; + } + + /** 查询易班用户信息。调用方检查响应状态和用户标识。 */ + public JSONObject userInfo(String accessToken) { + Assert.hasText(accessToken, "Yiban access token is required"); + return execute(new HttpGet(build(new URIBuilder(userEndpoint).addParameter("access_token", accessToken)))); + } + + private JSONObject execute(HttpUriRequest request) { + request.setHeader("Accept", "application/json"); + try (CloseableHttpResponse response = http.execute(request)) { + int status = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + if (status != HttpStatus.SC_OK || Objects.isNull(entity)) { + throw new AuthenticationServiceException("Yiban API did not return a successful response"); + } + JSONObject body = JSON.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8)); + if (Objects.isNull(body)) { + throw new AuthenticationServiceException("Yiban API returned an empty response"); + } + return body; + } catch (IOException | JSONException exception) { + // 请求地址或错误响应可包含令牌。对外传递固定错误消息。 + throw new AuthenticationServiceException("Unable to read the Yiban API response"); + } + } + + private static URI build(URIBuilder builder) { + try { + return builder.build(); + } catch (URISyntaxException exception) { + throw new AuthenticationServiceException("Invalid Yiban request URI"); + } + } + + @Override + public void close() throws IOException { + http.close(); + } +} diff --git a/src/main/java/org/springframework/security/boot/yiban/endpoint/YibanApiEndpoint.java b/src/main/java/org/springframework/security/boot/yiban/endpoint/YibanApiEndpoint.java index 0404a8e..55eab1f 100644 --- a/src/main/java/org/springframework/security/boot/yiban/endpoint/YibanApiEndpoint.java +++ b/src/main/java/org/springframework/security/boot/yiban/endpoint/YibanApiEndpoint.java @@ -1,37 +1,24 @@ package org.springframework.security.boot.yiban.endpoint; -import java.util.List; +import javax.servlet.http.HttpServletRequest; import org.springframework.http.ResponseEntity; +import org.springframework.security.boot.yiban.client.YibanAuthorizationState; +import org.springframework.security.boot.yiban.client.YibanOAuthClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import cn.yiban.open.Authorize; -import cn.yiban.open.Authorize.DISPLAY_TAG_T; - - @RestController("/yiban/api/") public class YibanApiEndpoint { - - private final Authorize authorize; - private final String redirect_uri; - private final String state; - private final Authorize.DISPLAY_TAG_T display; - - public YibanApiEndpoint(Authorize authorize, String redirect_uri, String state, - DISPLAY_TAG_T display) { - super(); - this.authorize = authorize; - this.redirect_uri = redirect_uri; - this.state = state; - this.display = display; - } - - @GetMapping("login") - public ResponseEntity list() throws Exception { - - String url = authorize.forwardurl(redirect_uri, state, display); - return ResponseEntity.ok(url); - } - + + private final YibanOAuthClient authorize; + + public YibanApiEndpoint(YibanOAuthClient authorize) { + this.authorize = authorize; + } + + @GetMapping("login") + public ResponseEntity list(HttpServletRequest request) { + return ResponseEntity.ok(authorize.authorizationUri(YibanAuthorizationState.issue(request)).toASCIIString()); + } } diff --git a/src/test/java/org/springframework/security/boot/yiban/YibanBoot23CompatibilityTest.java b/src/test/java/org/springframework/security/boot/yiban/YibanBoot23CompatibilityTest.java deleted file mode 100644 index f9c80e3..0000000 --- a/src/test/java/org/springframework/security/boot/yiban/YibanBoot23CompatibilityTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.springframework.security.boot.yiban; - -import cn.yiban.open.Authorize; -import cn.yiban.util.HTTPSimple; -import com.sun.net.httpserver.HttpServer; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.concurrent.atomic.AtomicInteger; -import org.apache.http.message.BasicNameValuePair; -import org.junit.jupiter.api.Test; -import org.springframework.boot.SpringBootVersion; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.boot.biz.userdetails.UserDetailsServiceAdapter; -import org.springframework.security.boot.yiban.authentication.YibanAuthenticationProvider; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class YibanBoot23CompatibilityTest { - - @Test - void startsServletSecurityWithThePublishedSecurityBizDependency() { - assertThat(SpringBootVersion.getVersion()).isEqualTo("2.3.12.RELEASE"); - assertThat(System.getProperty("java.specification.version")).isEqualTo("1.8"); - new WebApplicationContextRunner() - .withUserConfiguration(ServletApplication.class) - .withBean(UserDetailsServiceAdapter.class, () -> mock(UserDetailsServiceAdapter.class)) - .withPropertyValues("spring.security.yiban.enabled=true", - "spring.security.yiban.authc.app-key=local-fixture", - "spring.security.yiban.authc.app-secret=fixture-secret", - "spring.security.yiban.authc.callback=https://example.test/callback") - .run(context -> { - assertThat(context).hasSingleBean(Authorize.class) - .hasSingleBean(YibanAuthenticationProvider.class) - .hasBean("springSecurityFilterChain"); - assertThat(context.getBean(Authorize.class) - .forwardurl("https://example.test/callback", "fixture-state", Authorize.DISPLAY_TAG_T.WEB)) - .startsWith("https://openapi.yiban.cn/") - .contains("local-fixture", "fixture-state"); - }); - } - - @Test - void transportAcceptsFormResponsesWithoutFollowingRedirects() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); - AtomicInteger redirected = new AtomicInteger(); - server.createContext("/redirect", exchange -> { - exchange.getResponseHeaders().set("Location", "/destination"); - exchange.sendResponseHeaders(302, -1); - exchange.close(); - }); - server.createContext("/destination", exchange -> { - redirected.incrementAndGet(); - exchange.sendResponseHeaders(200, -1); - exchange.close(); - }); - server.createContext("/form", exchange -> { - byte[] body = "{\"access_token\":\"fixture\"}".getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(200, body.length); - exchange.getResponseBody().write(body); - exchange.close(); - }); - server.start(); - try { - String endpoint = "http://127.0.0.1:" + server.getAddress().getPort(); - assertThat(HTTPSimple.POST(endpoint + "/form", Collections.singletonList( - new BasicNameValuePair("code", "fixture")))).contains("access_token"); - assertThat(HTTPSimple.GET(endpoint + "/redirect")).isEmpty(); - assertThat(redirected.get()).isZero(); - } finally { - server.stop(0); - } - } - @Configuration(proxyBeanMethods = false) - @EnableAutoConfiguration - static class ServletApplication { - } -} diff --git a/src/test/java/org/springframework/security/boot/yiban/client/YibanOAuthFlowTest.java b/src/test/java/org/springframework/security/boot/yiban/client/YibanOAuthFlowTest.java new file mode 100644 index 0000000..61bca60 --- /dev/null +++ b/src/test/java/org/springframework/security/boot/yiban/client/YibanOAuthFlowTest.java @@ -0,0 +1,231 @@ +package org.springframework.security.boot.yiban.client; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.util.EntityUtils; +import org.apache.http.entity.BasicHttpEntity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.boot.biz.userdetails.UserDetailsServiceAdapter; +import org.springframework.security.boot.yiban.authentication.YibanAuthenticationProvider; +import org.springframework.security.boot.yiban.authentication.YibanAuthenticationToken; +import org.springframework.security.boot.yiban.authentication.YibanAuthorizationProcessingFilter; +import org.springframework.security.boot.yiban.authentication.YibanPreAuthenticatedProcessingFilter; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class YibanOAuthFlowTest { + + private static final String LOGIN = "/login/yiban"; + private static final String CALLBACK = "https://app.example.test/login/yiban?source=fixture"; + private static final String TOKEN = "fixture token+"; + private static final String CODE = "中文 +/="; + + private final AtomicInteger exchanges = new AtomicInteger(); + private final AtomicReference> form = new AtomicReference<>(); + private final AtomicReference> query = new AtomicReference<>(); + private final AtomicReference tokenResponse = new AtomicReference<>("{\"access_token\":\"fixture token+\"}"); + private final AtomicReference profileResponse = + new AtomicReference<>("{\"status\":\"success\",\"info\":{\"yb_userid\":\"user-1\"}}"); + + private HttpServer server; + private YibanOAuthClient client; + + @BeforeEach + void startGateway() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/token/info", exchange -> { + exchanges.incrementAndGet(); + BasicHttpEntity body = new BasicHttpEntity(); + body.setContent(exchange.getRequestBody()); + form.set(URLEncodedUtils.parse(EntityUtils.toString(body, StandardCharsets.UTF_8), StandardCharsets.UTF_8) + .stream().collect(Collectors.toMap(pair -> pair.getName(), pair -> pair.getValue()))); + respond(exchange, tokenResponse.get()); + }); + server.createContext("/user/me", exchange -> { + query.set(parameters(exchange.getRequestURI())); + respond(exchange, profileResponse.get()); + }); + server.start(); + URI base = URI.create("http://127.0.0.1:" + server.getAddress().getPort()); + client = new YibanOAuthClient("fixture-app", "fixture-secret", CALLBACK, + base.resolve("/code/authorize"), base.resolve("/token/info"), base.resolve("/user/me")); + } + + @AfterEach + void stopGateway() throws IOException { + try { + client.close(); + } finally { + server.stop(0); + } + } + + @Test + void exchangesOnlyTheMatchingCallbackAndAuthenticatesTheResolvedAccount() throws Exception { + UserDetailsServiceAdapter users = mock(UserDetailsServiceAdapter.class); + when(users.loadUserDetails(any(Authentication.class))) + .thenReturn(User.withUsername("local-user").password("unused").authorities("ROLE_USER").build()); + + YibanAuthenticationProvider provider = new YibanAuthenticationProvider(users, client); + YibanAuthorizationProcessingFilter callback = new YibanAuthorizationProcessingFilter(client); + callback.setAuthenticationManager(provider::authenticate); + YibanPreAuthenticatedProcessingFilter initiation = new YibanPreAuthenticatedProcessingFilter(client, LOGIN, "code"); + + MockHttpServletRequest start = request(); + MockHttpServletResponse outward = new MockHttpServletResponse(); + initiation.doFilter(start, outward, new MockFilterChain()); + URI redirect = URI.create(outward.getRedirectedUrl()); + assertThat(redirect.getPath()).isEqualTo("/code/authorize"); + Map auth = parameters(redirect); + assertThat(auth).containsEntry("client_id", "fixture-app").containsEntry("redirect_uri", CALLBACK) + .doesNotContainKey("client_secret"); + String state = auth.get("state"); + assertThat(state).isNotBlank(); + + MockHttpServletRequest denied = callback((MockHttpSession) start.getSession(), "invalid-state"); + assertThatThrownBy(() -> callback.doAttemptAuthentication(denied, new MockHttpServletResponse())) + .isInstanceOf(BadCredentialsException.class); + assertThat(exchanges.get()).isZero(); + + MockHttpServletRequest valid = callback((MockHttpSession) start.getSession(), state); + MockFilterChain forwarded = new MockFilterChain(); + initiation.doFilter(valid, new MockHttpServletResponse(), forwarded); + assertThat(forwarded.getRequest()).isSameAs(valid); + Authentication authenticated = callback.doAttemptAuthentication(valid, new MockHttpServletResponse()); + assertThat(authenticated.isAuthenticated()).isTrue(); + assertThat(authenticated.getName()).isEqualTo("local-user"); + assertThat(form.get()).containsEntry("code", CODE).containsEntry("client_id", "fixture-app") + .containsEntry("client_secret", "fixture-secret").containsEntry("redirect_uri", CALLBACK); + assertThat(query.get()).containsEntry("access_token", TOKEN); + + assertThatThrownBy(() -> callback.doAttemptAuthentication(valid, new MockHttpServletResponse())) + .isInstanceOf(BadCredentialsException.class); + assertThat(exchanges.get()).isEqualTo(1); + } + + @Test + void rejectsTheResponseWhenTheVendorDoesNotReturnAnAccessToken() { + tokenResponse.set("{\"error\":\"fixture-secret\"}"); + assertThatThrownBy(() -> client.exchangeCode(CODE)) + .isInstanceOf(AuthenticationServiceException.class) + .hasMessageNotContaining("fixture-secret"); + } + + @Test + void rejectsTheResponseWhenTheVendorDoesNotReturnAUserId() { + UserDetailsServiceAdapter users = mock(UserDetailsServiceAdapter.class); + YibanAuthenticationProvider provider = new YibanAuthenticationProvider(users, client); + profileResponse.set("{\"status\":\"success\",\"info\":{}}"); + assertThatThrownBy(() -> provider.authenticate( + new YibanAuthenticationToken(TOKEN))) + .isInstanceOf(BadCredentialsException.class); + } + + @Test + void handlesLoginAndCallbackThroughTheAutoConfiguredSecurityChain() { + UserDetailsServiceAdapter users = mock(UserDetailsServiceAdapter.class); + when(users.loadUserDetails(any(Authentication.class))) + .thenReturn(User.withUsername("local-user").password("unused").authorities("ROLE_USER").build()); + new WebApplicationContextRunner() + .withUserConfiguration(Application.class) + .withBean(YibanOAuthClient.class, () -> client, definition -> definition.setDestroyMethodName("")) + .withBean(UserDetailsServiceAdapter.class, () -> users) + .withPropertyValues("spring.security.yiban.enabled=true", + "spring.security.yiban.authc.app-key=fixture-app", + "spring.security.yiban.authc.app-secret=fixture-secret", + "spring.security.yiban.authc.callback=" + CALLBACK) + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(YibanOAuthClient.class); + assertThat(context).hasSingleBean(YibanAuthenticationProvider.class); + FilterChainProxy filters = context.getBean("springSecurityFilterChain", FilterChainProxy.class); + SecurityFilterChain yiban = filters.getFilterChains().stream() + .filter(chain -> chain.matches(request())).findFirst().get(); + assertThat(yiban.getFilters()).anyMatch(YibanPreAuthenticatedProcessingFilter.class::isInstance) + .anyMatch(YibanAuthorizationProcessingFilter.class::isInstance); + MockHttpServletRequest protectedRequest = new MockHttpServletRequest("GET", "/login"); + protectedRequest.setServletPath("/login"); + assertThat(filters.getFilterChains()) + .anyMatch(chain -> chain.matches(protectedRequest) && !chain.getFilters().isEmpty() + && chain.getFilters().stream().noneMatch(YibanAuthorizationProcessingFilter.class::isInstance)); + + MockHttpServletRequest start = request(); + MockHttpServletResponse redirect = new MockHttpServletResponse(); + filters.doFilter(start, redirect, new MockFilterChain()); + String state = parameters(URI.create(redirect.getRedirectedUrl())).get("state"); + assertThat(state).isNotBlank(); + + MockHttpSession session = (MockHttpSession) start.getSession(); + MockHttpServletResponse response = new MockHttpServletResponse(); + filters.doFilter(callback(session, state), response, new MockFilterChain()); + assertThat(exchanges.get()).isEqualTo(1); + assertThat(response.getStatus()).isLessThan(400); + assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNotNull(); + }); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application { + } + + private static void respond(HttpExchange exchange, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream response = exchange.getResponseBody()) { + response.write(bytes); + } finally { + exchange.close(); + } + } + + private static Map parameters(URI uri) { + return URLEncodedUtils.parse(uri, StandardCharsets.UTF_8).stream() + .collect(Collectors.toMap(pair -> pair.getName(), pair -> pair.getValue())); + } + + private static MockHttpServletRequest request() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", LOGIN); + request.setServletPath(LOGIN); + return request; + } + + private static MockHttpServletRequest callback(MockHttpSession session, String state) { + MockHttpServletRequest request = request(); + request.setSession(session); + request.addParameter("code", CODE); + request.addParameter("state", state); + return request; + } +}