新增加第三方登录授权功能

feature/model
thiszhc 1 year ago
parent 204d882a8e
commit e4b405491f

@ -41,6 +41,7 @@
<bouncycastle.version>1.72</bouncycastle.version>
<!-- 离线IP地址定位库 -->
<ip2region.version>2.7.0</ip2region.version>
<justauth.version>1.15.6</justauth.version>
<!-- 临时修复 snakeyaml 漏洞 -->
<snakeyaml.version>1.33</snakeyaml.version>
@ -291,6 +292,13 @@
<version>${snakeyaml.version}</version>
</dependency>
<!-- 第三方授权登录 -->
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
<version>${justauth.version}</version>
</dependency>
<!-- 加密包引入 -->
<dependency>
<groupId>org.bouncycastle</groupId>

@ -75,6 +75,21 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
</dependency>
<dependency>
<groupId>org.dromara</groupId>
<artifactId>ruoyi-common-auth</artifactId>
<version>5.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.2.4</version>
<scope>compile</scope>
</dependency>
<!-- skywalking 整合 logback -->
<!-- <dependency>-->

@ -2,9 +2,21 @@ package org.dromara.web.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.dromara.common.auth.utils.AuthUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.EmailLoginBody;
import org.dromara.common.core.domain.model.LoginBody;
@ -16,6 +28,8 @@ import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.system.service.ISysTenantService;
import org.dromara.web.domain.vo.LoginTenantVo;
@ -26,8 +40,11 @@ import org.dromara.web.service.SysRegisterService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
@ -41,10 +58,18 @@ import java.util.List;
@RequestMapping("/auth")
public class AuthController {
private AuthStateCache authStateCache;
private final SysLoginService loginService;
private final SysRegisterService registerService;
private final ISysConfigService configService;
private final ISysTenantService tenantService;
private final SysUserMapper userMapper;
private final Map<String, String> auths = new HashMap<>();
{
auths.put("gitee", "{\"clientId\":\"38eaaa1b77b5e064313057a2f5745ce3a9f3e7686d9bd302c7df2f308ef6db81\",\"clientSecret\":\"2e633af8780cb9fe002c4c7291b722db944402e271efb99b062811f52d7da1ff\",\"redirectUri\":\"http://127.0.0.1:8888/social-login?source=gitee\"}");
auths.put("github", "{\"clientId\":\"Iv1.1be0cdcd71aca63b\",\"clientSecret\":\"0d59d28b43152bc8906011624db37b0fed88d154\",\"redirectUri\":\"http://127.0.0.1:80/social-login?source=github\"}");
authStateCache = AuthDefaultStateCache.INSTANCE;// 使用默认的缓存
}
/**
*
@ -115,6 +140,64 @@ public class AuthController {
return R.ok(loginVo);
}
/**
*
* @param source
* @throws IOException
*/
@GetMapping("/binding/{source}")
@ResponseBody
public R<LoginVo> authBinding(@PathVariable("source") String source, HttpServletRequest request){
SysUserVo userLoding = new SysUserVo();
if (ObjectUtil.isNull(userLoding)) {
return R.fail("授权失败,请先登录再绑定");
}
if (userMapper.checkAuthUser(userLoding.getUserId(),source) > 0)
{
return R.fail(source + "平台账号已经绑定");
}
String obj = auths.get(source);
if (StringUtils.isEmpty(obj))
{
return R.fail(source + "平台账号暂不支持");
}
JSONObject json = JSONUtil.parseObj(obj);
AuthRequest authRequest = AuthUtils.getAuthRequest(source,
json.getStr("clientId"),
json.getStr("clientSecret"),
json.getStr("redirectUri"), authStateCache);
String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
return R.ok(authorizeUrl);
}
/**
* @param source
* @param callback
* @param request
* @return
*/
@SuppressWarnings("unchecked")
@GetMapping("/social-login/{source}")
public R<String> socialLogin(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request) throws IOException {
String obj = auths.get(source);
if (StringUtils.isEmpty(obj))
{
return R.fail("第三方平台系统不支持或未提供来源");
}
JSONObject json = JSONUtil.parseObj(obj);
AuthRequest authRequest = AuthUtils.getAuthRequest(source,
json.getStr("clientId"),
json.getStr("clientSecret"),
json.getStr("redirectUri"), authStateCache);
AuthResponse<AuthUser> response = authRequest.login(callback);
return loginService.socialLogin(source, response, request);
}
/**
* 退
*/

@ -6,11 +6,15 @@ import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.XcxLoginUser;
@ -28,6 +32,7 @@ import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.exception.TenantException;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.common.web.config.properties.CaptchaProperties;
import org.dromara.system.domain.SysAuthUser;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.domain.vo.SysUserVo;
@ -37,6 +42,7 @@ import org.dromara.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.List;
@ -154,6 +160,65 @@ public class SysLoginService {
return StpUtil.getTokenValue();
}
/**
*
* @param source
* @throws IOException
*/
/**
*
* @param source
* @param authUser
* @param request Http
* @return
* @throws IOException
*/
public R<String> socialLogin(String source, AuthResponse<AuthUser> authUser, HttpServletRequest request) throws IOException {
// 判断授权响应是否成功
if (!authUser.ok()) {
return R.fail("对不起,授权信息验证不通过,请联系管理员");
}
AuthUser authUserData = authUser.getData();
// 判断数据库中是否已存在该用户
SysUserVo user = userMapper.selectAuthUserByUuid(source + authUserData.getUuid());
if (ObjectUtil.isNotNull(user)) {
checkTenant(user.getTenantId());
SysUserVo dbUser = loadUserByUsername(user.getTenantId(), user.getUserName());
// 登录
LoginHelper.loginByDevice(buildLoginUser(dbUser), DeviceType.auth);
recordLogininfor(dbUser.getTenantId(), user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
recordLoginInfo(user.getUserId());
return R.ok(StpUtil.getTokenValue());
} else {
if (LoginHelper.getUserId() == null) {
return R.fail("授权失败,请先登录再绑定");
}
// 组装授权用户信息
SysAuthUser sysAuthUser = new SysAuthUser();
sysAuthUser.setAvatar(authUserData.getAvatar());
sysAuthUser.setUuid(source + authUserData.getUuid());
sysAuthUser.setUserId(LoginHelper.getUserId());
sysAuthUser.setUserName(authUserData.getUsername());
sysAuthUser.setNickName(authUserData.getNickname());
sysAuthUser.setEmail(authUserData.getEmail());
sysAuthUser.setSource(source);
sysAuthUser.setCreateTime(new Date().toString());
// 新用户,绑定第三方账号
userMapper.insertAuthUser(sysAuthUser);
SysUserVo lodingData = loadUserByUsername(LoginHelper.getTenantId(), LoginHelper.getUsername());
checkTenant(lodingData.getTenantId());
LoginHelper.loginByDevice(buildLoginUser(lodingData), DeviceType.auth);
recordLogininfor(lodingData.getTenantId(), sysAuthUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
recordLoginInfo(sysAuthUser.getUserId());
return R.ok(StpUtil.getTokenValue());
}
}
/**
* 退
*/

@ -11,6 +11,7 @@
<modules>
<module>ruoyi-common-bom</module>
<module>ruoyi-common-auth</module>
<module>ruoyi-common-core</module>
<module>ruoyi-common-doc</module>
<module>ruoyi-common-excel</module>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.dromara</groupId>
<artifactId>ruoyi-common</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-common-auth</artifactId>
<description>
ruoyi-common-auth 认证模块
</description>
<dependencies>
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,112 @@
package org.dromara.common.auth.utils;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.request.*;
/**
*
*
* @author ruoyi
*/
public class AuthUtils {
public static AuthRequest getAuthRequest(String source, String clientId, String clientSecret, String redirectUri,
AuthStateCache authStateCache)
{
AuthRequest authRequest = null;
switch (source.toLowerCase()) {
case "dingtalk" ->
authRequest = new AuthDingTalkRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "baidu" ->
authRequest = new AuthBaiduRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "github" ->
authRequest = new AuthGithubRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "gitee" ->
authRequest = new AuthGiteeRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "weibo" ->
authRequest = new AuthWeiboRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "coding" ->
authRequest = new AuthCodingRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).codingGroupName("").build(), authStateCache);
case "oschina" ->
authRequest = new AuthOschinaRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "alipay" ->
// 支付宝在创建回调地址时不允许使用localhost或者127.0.0.1所以这儿的回调地址使用的局域网内的ip
authRequest = new AuthAlipayRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.alipayPublicKey("").redirectUri(redirectUri).build(), authStateCache);
case "qq" ->
authRequest = new AuthQqRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "wechat_open" -> authRequest = new AuthWeChatOpenRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).build(), authStateCache);
case "csdn" ->
authRequest = new AuthCsdnRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "taobao" ->
authRequest = new AuthTaobaoRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "douyin" ->
authRequest = new AuthDouyinRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "linkedin" ->
authRequest = new AuthLinkedinRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "microsoft" -> authRequest = new AuthMicrosoftRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).build(), authStateCache);
case "mi" ->
authRequest = new AuthMiRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "toutiao" ->
authRequest = new AuthToutiaoRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "teambition" -> authRequest = new AuthTeambitionRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).build(), authStateCache);
case "pinterest" -> authRequest = new AuthPinterestRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).build(), authStateCache);
case "renren" ->
authRequest = new AuthRenrenRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "stack_overflow" -> authRequest = new AuthStackOverflowRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).stackOverflowKey("").build(),
authStateCache);
case "huawei" ->
authRequest = new AuthHuaweiRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "wechat_enterprise" ->
authRequest = new AuthWeChatEnterpriseRequest(AuthConfig.builder().clientId(clientId)
.clientSecret(clientSecret).redirectUri(redirectUri).agentId("").build(), authStateCache);
case "kujiale" ->
authRequest = new AuthKujialeRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "gitlab" ->
authRequest = new AuthGitlabRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "meituan" ->
authRequest = new AuthMeituanRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "eleme" ->
authRequest = new AuthElemeRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build());
case "wechat_mp" ->
authRequest = new AuthWeChatMpRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
case "aliyun" ->
authRequest = new AuthAliyunRequest(AuthConfig.builder().clientId(clientId).clientSecret(clientSecret)
.redirectUri(redirectUri).build(), authStateCache);
default -> {
}
}
if (null == authRequest)
{
throw new AuthException("未获取到有效的Auth配置");
}
return authRequest;
}
}

@ -26,7 +26,9 @@ public enum DeviceType {
/**
*
*/
XCX("xcx");
XCX("xcx"),
auth("auth");
private final String device;
}

@ -0,0 +1,40 @@
package org.dromara.system.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@TableName("sys_auth_user")
public class SysAuthUser {
private static final long serialVersionUID = 1L;
/** 授权ID */
private Long authId;
/** 第三方平台用户唯一ID */
private String uuid;
/** 系统用户ID */
private Long userId;
/** 登录账号 */
private String userName;
/** 用户昵称 */
private String nickName;
/** 头像地址 */
private String avatar;
/** 用户邮箱 */
private String email;
/** 用户来源 */
private String source;
private String createTime;
}

@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.dromara.common.mybatis.annotation.DataColumn;
import org.dromara.common.mybatis.annotation.DataPermission;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
import org.dromara.system.domain.SysAuthUser;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.apache.ibatis.annotations.Param;
@ -123,8 +124,8 @@ public interface SysUserMapper extends BaseMapperPlus<SysUser, SysUserVo> {
* @return
*/
@DataPermission({
@DataColumn(key = "deptName", value = "d.dept_id"),
@DataColumn(key = "userName", value = "u.user_id")
@DataColumn(key = "deptName", value = "d.dept_id"),// 部门权限
@DataColumn(key = "userName", value = "u.user_id")// 用户权限
})
SysUserVo selectUserById(Long userId);
@ -142,4 +143,44 @@ public interface SysUserMapper extends BaseMapperPlus<SysUser, SysUserVo> {
})
int updateById(@Param(Constants.ENTITY) SysUser user);
/**
*
*
* @param userId
* @return
*/
public List<SysAuthUser> selectAuthUserListByUserId(Long userId);
/**
* uuid
*
* @param uuid
* @return
*/
public SysUserVo selectAuthUserByUuid(String uuid);
/**
* source
*
* @param userId
* @param source
* @return
*/
public int checkAuthUser(@Param("userId") Long userId, @Param("source") String source);
/**
*
*
* @param authUser
* @return
*/
public int insertAuthUser(SysAuthUser authUser);
/**
*
*
* @param authId
* @return
*/
public int deleteAuthUser(Long authId);
}

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.system.mapper.SysUserMapper">
<resultMap id="SysAuthUserResult" type="org.dromara.system.domain.SysAuthUser">
<id property="authId" column="auth_id" />
<result property="uuid" column="uuid" />
<result property="userId" column="user_id" />
<result property="userName" column="user_name" />
<result property="nickName" column="nick_name" />
<result property="avatar" column="avatar" />
<result property="email" column="email" />
<result property="source" column="source" />
<result property="createTime" column="create_time" />
</resultMap>
<select id="selectAuthUserByUuid" parameterType="String" resultMap="SysUserResult">
select b.user_id as user_id, b.user_name as user_name, b.password as password , a.tenant_id as tenant_id
from sys_auth_user a left join sys_user b on a.user_id = b.user_id
where a.uuid = #{uuid} and b.del_flag = '0'
</select>
<select id="selectAuthUserListByUserId" parameterType="Long" resultMap="SysAuthUserResult">
select auth_id, uuid, user_id, user_name, nick_name, avatar, email, source, create_time, tenant_id from sys_auth_user where user_id = #{userId}
</select>
<select id="checkAuthUser" parameterType="org.dromara.system.domain.SysAuthUser" resultType="int">
select count(1) from sys_auth_user where user_id=#{userId} and source=#{source} limit 1
</select>
<insert id="insertAuthUser" parameterType="org.dromara.system.domain.SysAuthUser">
insert into sys_auth_user(
<if test="uuid != null and uuid != ''">uuid,</if>
<if test="userId != null and userId != 0">user_id,</if>
<if test="userName != null and userName != ''">user_name,</if>
<if test="nickName != null and nickName != ''">nick_name,</if>
<if test="avatar != null and avatar != ''">avatar,</if>
<if test="email != null and email != ''">email,</if>
<if test="source != null and source != ''">source,</if>
create_time
)values(
<if test="uuid != null and uuid != ''">#{uuid},</if>
<if test="userId != null and userId != 0">#{userId},</if>
<if test="userName != null and userName != ''">#{userName},</if>
<if test="nickName != null and nickName != ''">#{nickName},</if>
<if test="avatar != null and avatar != ''">#{avatar},</if>
<if test="email != null and email != ''">#{email},</if>
<if test="source != null and source != ''">#{source},</if>
now()
)
</insert>
<delete id="deleteAuthUser" parameterType="Long">
delete from sys_auth_user where auth_id = #{authId}
</delete>
</mapper>

@ -0,0 +1,14 @@
CREATE TABLE `sys_auth_user` (
`auth_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '授权ID',
`uuid` varchar(500) NOT NULL COMMENT '第三方平台用户唯一ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '系统用户ID',
`user_name` varchar(30) NOT NULL COMMENT '登录账号',
`nick_name` varchar(30) DEFAULT '' COMMENT '用户昵称',
`avatar` varchar(500) DEFAULT '' COMMENT '头像地址',
`email` varchar(255) DEFAULT '' COMMENT '用户邮箱',
`source` varchar(255) DEFAULT '' COMMENT '用户来源',
` tenant_id` varchar(20) DEFAULT '000000' COMMENT '租户id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`tenant_id` varchar(25) NOT NULL DEFAULT '000000',
PRIMARY KEY (`auth_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT CHARSET=utf8mb4 COMMENT='第三方平台授权用户信息表';
Loading…
Cancel
Save