!183 OAuth 2.0登录支持

Merge pull request !183 from MaxKeyTop/master
This commit is contained in:
不忘初心 2023-03-26 12:20:57 +00:00 committed by Gitee
commit ad30295913
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
10 changed files with 298 additions and 1 deletions

View File

@ -129,6 +129,11 @@
<artifactId>storage-module-mysql</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
<version>1.16.5</version>
</dependency>
</dependencies>
<build>
<resources>

View File

@ -205,6 +205,13 @@ public class IndexControl extends BaseServerController {
// InputStream inputStream = ResourceUtil.getStream("classpath:/logo/favicon.ico");
// ServletUtil.write(response, inputStream, MediaType.IMAGE_PNG_VALUE);
}
@RequestMapping(value = "oauth2_image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
@NotLogin
public void oauth2Image(HttpServletResponse response) throws IOException {
String logoFile = webConfig.getLogoFile();
this.loadImage(response, logoFile, "classpath:/logo/oauth2.png", "jpg", "png", "gif");
}
private void loadImage(HttpServletResponse response, String imgFile, String defaultResource, String... suffix) throws IOException {
if (StrUtil.isNotEmpty(imgFile)) {

View File

@ -46,6 +46,8 @@ import io.jpom.func.user.server.UserLoginLogServer;
import io.jpom.model.data.WorkspaceModel;
import io.jpom.model.dto.UserLoginDto;
import io.jpom.model.user.UserModel;
import io.jpom.oauth2.AuthOauth2CustomRequest;
import io.jpom.oauth2.Oauth2AuthSource;
import io.jpom.permission.ClassFeature;
import io.jpom.permission.Feature;
import io.jpom.service.user.UserBindWorkspaceService;
@ -56,12 +58,18 @@ import io.jpom.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
@ -89,6 +97,9 @@ public class LoginControl extends BaseServerController {
private final ServerConfig.UserConfig userConfig;
private final ServerConfig.WebConfig webConfig;
private final UserLoginLogServer userLoginLogServer;
private final ServerConfig.OauthConfig oauthConfig;
private AuthOauth2CustomRequest authOauth2Request;
public LoginControl(UserService userService,
UserBindWorkspaceService userBindWorkspaceService,
@ -98,7 +109,16 @@ public class LoginControl extends BaseServerController {
this.userBindWorkspaceService = userBindWorkspaceService;
this.userConfig = serverConfig.getUser();
this.webConfig = serverConfig.getWeb();
this.oauthConfig = serverConfig.getOauth2();
this.userLoginLogServer = userLoginLogServer;
AuthConfig authConfig = AuthConfig.builder()
.clientId(oauthConfig.getClientId())
.clientSecret(oauthConfig.getClientSecret())
.redirectUri(oauthConfig.getRedirectUri())
.build();
authOauth2Request = new AuthOauth2CustomRequest( authConfig , new Oauth2AuthSource(oauthConfig));
}
/**
@ -154,6 +174,7 @@ public class LoginControl extends BaseServerController {
return count > userConfig.getAlwaysIpLoginError();
}
/**
* 登录接口
*
@ -228,6 +249,63 @@ public class LoginControl extends BaseServerController {
}
}
}
/**
* oauth 状态检查
* @param response
* @return json
* @throws IOException
*/
@RequestMapping(value = "oauth2/state", method = RequestMethod.GET)
@ResponseBody
@NotLogin
public HashMap<String,Object> oauth2LoginState(HttpServletResponse response) throws IOException {
HashMap<String,Object> data = new HashMap<String,Object>();
data.put("code", 200);
data.put("enabled", oauthConfig.isEnabled());
return data;
}
/**
* 跳转到认证中心登录
* @param request
* @return
*/
@GetMapping(value = "oauth2/login")
@NotLogin
public ModelAndView oauth2Login(HttpServletRequest request){
return new ModelAndView("redirect:" + authOauth2Request.authorize(null));
}
/**
* oauth2 登录并获取token
* @param code
* @param state
* @param request
* @return
*/
@PostMapping(value = "oauth2/login", produces = MediaType.APPLICATION_JSON_VALUE)
@NotLogin
public JsonMessage<Object> oauth2Callback(
@RequestParam(value = "code", required = true) String code,
@RequestParam(value = "state", required = false)String state,
HttpServletRequest request){
AuthCallback authCallback = new AuthCallback();
authCallback.setCode(code);
authCallback.setState(state);
AuthResponse<?> authResponse = authOauth2Request.login(authCallback);
AuthUser authUser = (AuthUser)authResponse.getData();
if(authUser != null) {
UserModel userModel = userService.getByKey(authUser.getUsername());
if (userModel == null) {
return new JsonMessage<>(400, "OAuth 2 登录失败,用户不存在请联系管理员!");
}
UserLoginDto userLoginDto = this.createToken(userModel);
userLoginLogServer.success(userModel, false, request);
return new JsonMessage<>(200, "OAuth 2 登录成功", userLoginDto);
}
return new JsonMessage<>(400, "OAuth 2 登录失败,请联系管理员!");
}
private UserLoginDto createToken(UserModel userModel) {
// 判断工作空间

View File

@ -0,0 +1,72 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Code Technology Studio
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.jpom.oauth2;
import com.alibaba.fastjson2.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
public class AuthOauth2CustomRequest extends AuthDefaultRequest {
public AuthOauth2CustomRequest(AuthConfig config, AuthSource source) {
super(config, source);
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
String body = doPostAuthorizationCode(authCallback.getCode());
JSONObject object = JSONObject.parseObject(body);
AuthToken authToken =
AuthToken.builder()
.accessToken(object.getString("access_token"))
.refreshToken(object.getString("refresh_token"))
.idToken(object.getString("id_token"))
.tokenType(object.getString("token_type"))
.scope(object.getString("scope"))
.build();
return authToken;
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String body = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(body);
AuthUser authUser =
AuthUser.builder()
.uuid(object.getString("id"))
.username(object.getString("username"))
.nickname(object.getString("name"))
.company(object.getString("organization"))
.email(object.getString("email"))
.token(authToken)
.source(source.toString())
.build();
return authUser;
}
}

View File

@ -0,0 +1,59 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Code Technology Studio
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.jpom.oauth2;
import io.jpom.system.ServerConfig;
import io.jpom.system.ServerConfig.OauthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.request.AuthDefaultRequest;
public class Oauth2AuthSource implements AuthSource{
ServerConfig.OauthConfig oauthConfig;
public Oauth2AuthSource(OauthConfig oauthConfig) {
super();
this.oauthConfig = oauthConfig;
}
@Override
public String authorize() {
return oauthConfig.getAuthorizationUri();
}
@Override
public String accessToken() {
return oauthConfig.getAccessTokenUri();
}
@Override
public String userInfo() {
return oauthConfig.getUserInfoUri();
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
// TODO Auto-generated method stub
return AuthOauth2CustomRequest.class;
}
}

View File

@ -104,6 +104,15 @@ public class ServerConfig extends BaseExtConfig {
});
}
private OauthConfig oauth2;
public OauthConfig getOauth2() {
return Optional.ofNullable(this.oauth2).orElseGet(() -> {
this.oauth2 = new OauthConfig();
return this.oauth2;
});
}
/**
* 获取当前登录用户的临时文件存储路径如果没有登录则抛出异常
*
@ -144,6 +153,18 @@ public class ServerConfig extends BaseExtConfig {
return file;
}
@Data
public static class OauthConfig{
private boolean enabled;
private String clientId;
private String clientSecret;
private String authorizationUri;
private String accessTokenUri;
private String userInfoUri;
private String redirectUri;
}
@Data
public static class WebConfig {

View File

@ -98,6 +98,15 @@ jpom:
pool-wait-queue: 10
# 日志显示 压缩折叠显示进度比例 范围 1-100
log-reduce-progress-ratio: 5
oauth2:
enabled: false
clientId: 837136275440926720
clientSecret: 8453MjUwMzIwMjMyMjQxNDY5MzYSD5
serverUrl: http://sso.maxkey.top
authorizationUri: ${jpom.oauth2.serverUrl}/sign/authz/oauth/v20/authorize
accessTokenUri: ${jpom.oauth2.serverUrl}/sign/authz/oauth/v20/token
userInfoUri: ${jpom.oauth2.serverUrl}/sign/api/oauth/v20/me
redirectUri: http://localhost:3000/
server:
#运行端口号
port: 2122
@ -120,6 +129,7 @@ server:
tomcat:
uri-encoding: UTF-8
connection-timeout: 10M
spring:
profiles:
active: mysql-1
@ -141,3 +151,5 @@ spring:
# 是否允许远程访问(开启此配置有安全风险),默认为 false当部署到服务器上之后是否可以通过其他浏览器访问数据库
settings:
web-allow-others: false

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -9,6 +9,23 @@ export function login(params) {
});
}
// oauth2Login
export function oauth2Login(params) {
return axios({
url: "/oauth2/login",
method: "post",
data: params,
});
}
export function oauth2State(params) {
return axios({
url: "/oauth2/state",
method: "get",
data: params,
});
}
/**
* 验证输入的验证码
* @param {JSON} params

View File

@ -49,6 +49,12 @@
</a-row>
</a-form-model-item>
<a-button type="primary" html-type="submit" class="btn-login"> 登录 </a-button>
<a-form-model-item v-if="this.enabledOauth2Login" :wrapper-col="{ span: 24 }" >
第三方登录
</a-form-model-item>
<a-form-model-item v-if="this.enabledOauth2Login" :wrapper-col="{ span: 24 }" >
<a href="/oauth2/login"><img src="/oauth2_image" width="32px;"></a>
</a-form-model-item>
</a-form-model>
</template>
<template v-if="this.action === 'mfa'">
@ -64,7 +70,7 @@
</div>
</template>
<script>
import { login, demoInfo, mfaVerify } from "@/api/user/user";
import { login, demoInfo, mfaVerify ,oauth2State,oauth2Login} from "@/api/user/user";
import { checkSystem } from "@/api/install";
import sha1 from "js-sha1";
@ -92,12 +98,25 @@ export default {
],
},
disabledCaptcha: false,
enabledOauth2Login:false,
};
},
created() {
this.checkSystem();
//this.getBg();
if(this.$route.query.code){
oauth2Login({code:this.$route.query.code,state:this.$route.query.state}).then((res) => {
//
if (res.code !== 200) {
//this.changeCode();
} else {
this.startDispatchLogin(res);
}
});
}
this.changeCode();
this.oauth2LoginCheck();
this.getDemoInfo();
},
computed: {
@ -154,6 +173,13 @@ export default {
// change Code
changeCode() {
this.randCode = "randCode.png?r=" + new Date().getTime();
},
//Check Oauth2 Login enabled
oauth2LoginCheck() {
oauth2State(null).then((res) => {
this.enabledOauth2Login = res.enabled;
console.log("enabled Oauth2 Login " + this.enabledOauth2Login);
});
},
// login
handleLogin(e) {