-
Notifications
You must be signed in to change notification settings - Fork 62
feat: 兼容原登录系统的基础上,接入 Maa Account #138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Lixuhuilll
wants to merge
11
commits into
ZOOT-Plus:dev
Choose a base branch
from
Lixuhuilll:switch-on-maa_account
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+386
−13
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
48236fc
兼容原登录系统的基础上,接入 Maa Account。
Lixuhuilll 72039ad
修改了登录请求的流程,不再使用 Session 作为缓存工具
Lixuhuilll b17b87f
存在匹配的邮箱则自动激活
Lixuhuilll 182e388
实现当配置文件中没有 Maa Account 配置时,关闭 OIDC 认证
Lixuhuilll 1c15be5
RedisCache 适配 Spring Security,RedisOAuth2AuthorizationRequestReposito…
Lixuhuilll 8878d1d
Merge branch 'MaaAssistantArknights:dev' into switch-on-maa_account
Lixuhuilll d25cdd8
调整 RedisCache 中的 ObjectMapper 配置
Lixuhuilll 700148a
优化循环依赖的解决方法
Lixuhuilll 928bc05
改进的密码编码器,便于在现有密码编码器不安全后快速替换
Lixuhuilll 52dea7b
用户使用密码登录时,自动升级密码编码方式
Lixuhuilll 7670511
Merge remote-tracking branch 'MaaBackendCenter/dev' into switch-on-ma…
Lixuhuilll File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
src/main/java/plus/maa/backend/config/security/OIDCAuthenticationSuccessHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| package plus.maa.backend.config.security; | ||
|
|
||
| import cn.hutool.core.lang.Assert; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; | ||
| import org.springframework.stereotype.Component; | ||
| import plus.maa.backend.common.utils.WebUtils; | ||
| import plus.maa.backend.controller.response.MaaResult; | ||
| import plus.maa.backend.controller.response.user.MaaLoginRsp; | ||
| import plus.maa.backend.repository.UserRepository; | ||
| import plus.maa.backend.repository.entity.MaaUser; | ||
| import plus.maa.backend.service.UserService; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| /** | ||
| * 适配 Maa Account | ||
| * | ||
| * @author lixuhuilll | ||
| * Date 2023/9/22 | ||
| */ | ||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OIDCAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { | ||
|
|
||
| private final ObjectMapper objectMapper; | ||
| private final UserRepository userRepository; | ||
| private final UserService userService; | ||
|
|
||
| @Override | ||
| public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { | ||
| try { | ||
| authenticationSuccess(request, response, authentication); | ||
| } catch (AuthenticationException e) { | ||
| throw e; | ||
| } catch (RuntimeException e) { | ||
| // 将运行时异常转换为 AuthenticationException 的子类型,触发统一的异常响应 | ||
| throw new OIDCAuthenticationException(e.getMessage()); | ||
| } finally { | ||
| // 删除在身份验证过程中可能已存储在会话中的临时身份验证相关数据 | ||
| clearAuthenticationAttributes(request); | ||
| } | ||
| } | ||
|
|
||
| public void authenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { | ||
| if (!(authentication instanceof OAuth2AuthenticationToken oauth2Token)) { | ||
| throw new OIDCAuthenticationException("无法取得授权信息"); | ||
| } | ||
|
|
||
| OAuth2User oAuth2User = oauth2Token.getPrincipal(); | ||
|
|
||
| String email = oAuth2User.getAttribute("email"); | ||
| Assert.notBlank(email, "无法取得邮箱"); | ||
|
|
||
| MaaUser maaUser = userRepository.findByEmail(email); | ||
| if (maaUser == null) { | ||
| // 如果不存在绑定好的邮箱,则注册新用户 | ||
| String userName = oAuth2User.getAttribute("preferred_username"); | ||
| Assert.notBlank(userName, "无法取得用户名"); | ||
|
|
||
| maaUser = new MaaUser() | ||
| .setUserName(userName) | ||
| .setEmail(email) | ||
| .setStatus(1); | ||
| maaUser = userRepository.save(maaUser); | ||
| } else if (maaUser.getStatus() == null || maaUser.getStatus() == 0) { | ||
| // 存在对应邮箱的用户但未激活时,自动激活 | ||
| maaUser.setStatus(1); | ||
| userRepository.save(maaUser); | ||
| } | ||
|
|
||
| // 响应登录数据 | ||
| MaaResult<MaaLoginRsp> result = MaaResult.success("登陆成功", userService.maaLoginRsp(maaUser)); | ||
| String json = objectMapper.writeValueAsString(result); | ||
| WebUtils.renderString(response, json, 200); | ||
| } | ||
|
|
||
| static class OIDCAuthenticationException extends AuthenticationException { | ||
| public OIDCAuthenticationException(String msg) { | ||
| super(msg); | ||
| } | ||
| } | ||
| } | ||
36 changes: 36 additions & 0 deletions
36
src/main/java/plus/maa/backend/config/security/OIDCRedirectStrategy.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| package plus.maa.backend.config.security; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.core.log.LogMessage; | ||
| import org.springframework.security.web.DefaultRedirectStrategy; | ||
| import org.springframework.stereotype.Component; | ||
| import plus.maa.backend.common.utils.WebUtils; | ||
| import plus.maa.backend.controller.response.MaaResult; | ||
| import plus.maa.backend.controller.response.user.OIDCInfo; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OIDCRedirectStrategy extends DefaultRedirectStrategy { | ||
|
|
||
| private final ObjectMapper objectMapper; | ||
|
|
||
| @Override | ||
| public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { | ||
| String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); | ||
| redirectUrl = response.encodeRedirectURL(redirectUrl); | ||
| if (this.logger.isDebugEnabled()) { | ||
| this.logger.debug(LogMessage.format("Redirecting to %s", redirectUrl)); | ||
| } | ||
| // 不再重定向,而是响应流水号和目标地址 | ||
| String serial = (String) request.getAttribute(RedisOAuth2AuthorizationRequestRepository.getREQUEST_KEY()); | ||
| OIDCInfo oidcInfo = new OIDCInfo(serial, redirectUrl); | ||
| MaaResult<OIDCInfo> result = MaaResult.success(oidcInfo); | ||
| String json = objectMapper.writeValueAsString(result); | ||
| WebUtils.renderString(response, json, 200); | ||
| } | ||
| } |
93 changes: 93 additions & 0 deletions
93
...main/java/plus/maa/backend/config/security/RedisOAuth2AuthorizationRequestRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| package plus.maa.backend.config.security; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; | ||
| import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; | ||
| import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.util.Assert; | ||
| import plus.maa.backend.repository.RedisCache; | ||
|
|
||
| import java.util.UUID; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| /** | ||
| * 使用本储存库储存 OAuth2AuthorizationRequest 时,前端的回调请求必须携带流水号 | ||
| * 流水号必须在 HTTP_HEAD_NAME 所指示的 Http Head 中,否则将提示 [authorization_request_not_found] | ||
| * | ||
| * @author lixuhuilll | ||
| * Date 2023/9/22 | ||
| */ | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class RedisOAuth2AuthorizationRequestRepository | ||
| implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> { | ||
|
|
||
| private static final String REDIS_KEY_PREFIX = "oidc:serial:"; | ||
| @Getter | ||
| private static final String REQUEST_KEY = "oidc_serial"; | ||
| private static final String HTTP_HEAD_NAME = "OIDC-Serial"; | ||
| // 默认缓存 20 分钟,超过 20 分钟后,授权必然失败,用户需要在 20 分钟内从 Maa Account 回调回来 | ||
| private static final int TIMEOUT = 60 * 20; | ||
|
|
||
| private final RedisCache redisCache; | ||
|
|
||
| @Override | ||
| public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { | ||
| Assert.notNull(request, "request cannot be null"); | ||
| String stateParameter = getStateParameter(request); | ||
| if (stateParameter == null) { | ||
| return null; | ||
| } | ||
| OAuth2AuthorizationRequest authorizationRequest = getAuthorizationRequest(request); | ||
| return (authorizationRequest != null && stateParameter.equals(authorizationRequest.getState())) | ||
| ? authorizationRequest : null; | ||
| } | ||
|
|
||
| @Override | ||
| public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { | ||
| Assert.notNull(request, "request cannot be null"); | ||
| Assert.notNull(response, "response cannot be null"); | ||
| if (authorizationRequest == null) { | ||
| removeAuthorizationRequest(request, response); | ||
| return; | ||
| } | ||
| String state = authorizationRequest.getState(); | ||
| Assert.hasText(state, "authorizationRequest.state cannot be empty"); | ||
| // 不再使用 Session | ||
| String serial = UUID.randomUUID().toString(); | ||
| request.setAttribute(REQUEST_KEY, serial); | ||
| redisCache.setCache(REDIS_KEY_PREFIX + serial, authorizationRequest, TIMEOUT, TimeUnit.SECONDS); | ||
| } | ||
|
|
||
| @Override | ||
| public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) { | ||
| Assert.notNull(response, "response cannot be null"); | ||
| OAuth2AuthorizationRequest authorizationRequest = loadAuthorizationRequest(request); | ||
| if (authorizationRequest != null) { | ||
| redisCache.removeCache(REDIS_KEY_PREFIX + getSerial(request)); | ||
| } | ||
| return authorizationRequest; | ||
| } | ||
|
|
||
| private String getStateParameter(HttpServletRequest request) { | ||
| return request.getParameter(OAuth2ParameterNames.STATE); | ||
| } | ||
|
|
||
| private String getSerial(HttpServletRequest request) { | ||
| String serial = (String) request.getAttribute(REQUEST_KEY); | ||
| if (serial == null) { | ||
| serial = request.getHeader(HTTP_HEAD_NAME); | ||
| } | ||
| return serial; | ||
| } | ||
|
|
||
| private OAuth2AuthorizationRequest getAuthorizationRequest(HttpServletRequest request) { | ||
| String serial = getSerial(request); | ||
| return redisCache.getCache(REDIS_KEY_PREFIX + serial, OAuth2AuthorizationRequest.class); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.