第三方登录规范(基础模块搭建)完成,微信小程序登录完成

This commit is contained in:
D 2024-01-18 02:44:33 +08:00
parent 4e0c8d3f1b
commit 5045483e01
16 changed files with 1109 additions and 28 deletions

View File

@ -4,5 +4,6 @@
"*.yml": "yaml" "*.yml": "yaml"
}, },
"java.compile.nullAnalysis.mode": "disabled", "java.compile.nullAnalysis.mode": "disabled",
"maven.view": "hierarchical",
// "java.compile.nullAnalysis.mode": "automatic" // "java.compile.nullAnalysis.mode": "automatic"
} }

View File

@ -2,10 +2,10 @@
wx: wx:
miniapp: miniapp:
open: true open: true
appId: miniAppid appId: wx2dd450adc727b59e
appSecret: miniAppSercret appSecret: 471e9abe00b93460d6a8654a30b4c85f
url: https://api.weixin.qq.com/sns/jscode2session url: https://api.weixin.qq.com/sns/jscode2session
h5: pub:
open: true open: true
appId: wx98501e665b0f0596 appId: wx98501e665b0f0596
appSecret: wx98501e665b0f0596 appSecret: wx98501e665b0f0596

View File

@ -3,7 +3,7 @@ package ${packageName}.domain;
#foreach ($import in $importList) #foreach ($import in $importList)
import ${import}; import ${import};
#end #end
import io.swagger.annotations.ApiModelProperty; import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel;

View File

@ -28,6 +28,20 @@
<version>${ruoyi.version}</version> <version>${ruoyi.version}</version>
</dependency> </dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 第三方认证通用工具--> <!-- 第三方认证通用工具-->
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>

View File

@ -23,6 +23,20 @@
<artifactId>ruoyi-common</artifactId> <artifactId>ruoyi-common</artifactId>
</dependency> </dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!--httpclient--> <!--httpclient-->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>

View File

@ -0,0 +1,113 @@
package com.ruoyi.oauth.common.controller;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.oauth.common.domain.OauthUser;
import com.ruoyi.oauth.common.service.IOauthUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
/**
* 第三方认证Controller
*
* @author ruoyi
* @date 2024-01-18
*/
@RestController
@RequestMapping("/system/oauth")
@Tag(name = "【第三方认证】管理")
public class OauthUserController extends BaseController
{
@Autowired
private IOauthUserService oauthUserService;
/**
* 查询第三方认证列表
*/
@Operation(summary = "查询第三方认证列表")
@PreAuthorize("@ss.hasPermi('system:oauth:list')")
@GetMapping("/list")
public TableDataInfo list(OauthUser oauthUser)
{
startPage();
List<OauthUser> list = oauthUserService.selectOauthUserList(oauthUser);
return getDataTable(list);
}
/**
* 导出第三方认证列表
*/
@Operation(summary = "导出第三方认证列表")
@PreAuthorize("@ss.hasPermi('system:oauth:export')")
@Log(title = "第三方认证", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, OauthUser oauthUser)
{
List<OauthUser> list = oauthUserService.selectOauthUserList(oauthUser);
ExcelUtil<OauthUser> util = new ExcelUtil<OauthUser>(OauthUser.class);
util.exportExcel(response, list, "第三方认证数据");
}
/**
* 获取第三方认证详细信息
*/
@Operation(summary = "获取第三方认证详细信息")
@PreAuthorize("@ss.hasPermi('system:oauth:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return success(oauthUserService.selectOauthUserById(id));
}
/**
* 新增第三方认证
*/
@Operation(summary = "新增第三方认证")
@PreAuthorize("@ss.hasPermi('system:oauth:add')")
@Log(title = "第三方认证", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody OauthUser oauthUser)
{
return toAjax(oauthUserService.insertOauthUser(oauthUser));
}
/**
* 修改第三方认证
*/
@Operation(summary = "修改第三方认证")
@PreAuthorize("@ss.hasPermi('system:oauth:edit')")
@Log(title = "第三方认证", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody OauthUser oauthUser)
{
return toAjax(oauthUserService.updateOauthUser(oauthUser));
}
/**
* 删除第三方认证
*/
@Operation(summary = "删除第三方认证")
@PreAuthorize("@ss.hasPermi('system:oauth:remove')")
@Log(title = "第三方认证", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable( name = "ids" ) Long[] ids)
{
return toAjax(oauthUserService.deleteOauthUserByIds(ids));
}
}

View File

@ -0,0 +1,407 @@
package com.ruoyi.oauth.common.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 第三方认证对象 oauth_user
*
* @author ruoyi
* @date 2024-01-18
*/
@Schema(description = "第三方认证对象")
public class OauthUser extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
@Schema(defaultValue = "主键")
private Long id;
/** 第三方系统的唯一ID详细解释请参考名词解释 */
@Schema(defaultValue = "第三方系统的唯一ID详细解释请参考名词解释")
@Excel(name = "第三方系统的唯一ID详细解释请参考名词解释")
private String uuid;
/** 用户ID */
@Schema(defaultValue = "用户ID")
@Excel(name = "用户ID")
private Long userId;
/** 第三方用户来源可选值GITHUB、GITEE、QQ更多请参考AuthDefaultSource.java(opens new window) */
@Schema(defaultValue = "第三方用户来源可选值GITHUB、GITEE、QQ更多请参考AuthDefaultSource.java(opens new window)")
@Excel(name = "第三方用户来源可选值GITHUB、GITEE、QQ更多请参考AuthDefaultSource.java(opens new window)")
private String source;
/** 用户的授权令牌 */
@Schema(defaultValue = "用户的授权令牌")
@Excel(name = "用户的授权令牌")
private String accessToken;
/** 第三方用户的授权令牌的有效期,部分平台可能没有 */
@Schema(defaultValue = "第三方用户的授权令牌的有效期,部分平台可能没有")
@Excel(name = "第三方用户的授权令牌的有效期,部分平台可能没有")
private Long expireIn;
/** 刷新令牌,部分平台可能没有 */
@Schema(defaultValue = "刷新令牌,部分平台可能没有")
@Excel(name = "刷新令牌,部分平台可能没有")
private String refreshToken;
/** 第三方用户的 open id部分平台可能没有 */
@Schema(defaultValue = "第三方用户的 open id部分平台可能没有")
@Excel(name = "第三方用户的 open id部分平台可能没有")
private String openId;
/** 第三方用户的 ID部分平台可能没有 */
@Schema(defaultValue = "第三方用户的 ID部分平台可能没有")
@Excel(name = "第三方用户的 ID部分平台可能没有")
private String uid;
/** 个别平台的授权信息,部分平台可能没有 */
@Schema(defaultValue = "个别平台的授权信息,部分平台可能没有")
@Excel(name = "个别平台的授权信息,部分平台可能没有")
private String accessCode;
/** 第三方用户的 union id部分平台可能没有 */
@Schema(defaultValue = "第三方用户的 union id部分平台可能没有")
@Excel(name = "第三方用户的 union id部分平台可能没有")
private String unionId;
/** 第三方用户授予的权限,部分平台可能没有 */
@Schema(defaultValue = "第三方用户授予的权限,部分平台可能没有")
@Excel(name = "第三方用户授予的权限,部分平台可能没有")
private String scope;
/** 个别平台的授权信息,部分平台可能没有 */
@Schema(defaultValue = "个别平台的授权信息,部分平台可能没有")
@Excel(name = "个别平台的授权信息,部分平台可能没有")
private String tokenType;
/** id token部分平台可能没有 */
@Schema(defaultValue = "id token部分平台可能没有")
@Excel(name = "id token部分平台可能没有")
private String idToken;
/** 小米平台用户的附带属性,部分平台可能没有 */
@Schema(defaultValue = "小米平台用户的附带属性,部分平台可能没有")
@Excel(name = "小米平台用户的附带属性,部分平台可能没有")
private String macAlgorithm;
/** 小米平台用户的附带属性,部分平台可能没有 */
@Schema(defaultValue = "小米平台用户的附带属性,部分平台可能没有")
@Excel(name = "小米平台用户的附带属性,部分平台可能没有")
private String macKey;
/** 用户的授权code部分平台可能没有 */
@Schema(defaultValue = "用户的授权code部分平台可能没有")
@Excel(name = "用户的授权code部分平台可能没有")
private String code;
/** Twitter平台用户的附带属性部分平台可能没有 */
@Schema(defaultValue = "Twitter平台用户的附带属性部分平台可能没有")
@Excel(name = "Twitter平台用户的附带属性部分平台可能没有")
private String oauthToken;
/** Twitter平台用户的附带属性部分平台可能没有 */
@Schema(defaultValue = "Twitter平台用户的附带属性部分平台可能没有")
@Excel(name = "Twitter平台用户的附带属性部分平台可能没有")
private String oauthTokenSecret;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setUuid(String uuid)
{
this.uuid = uuid;
}
public String getUuid()
{
return uuid;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setSource(String source)
{
this.source = source;
}
public String getSource()
{
return source;
}
public void setAccessToken(String accessToken)
{
this.accessToken = accessToken;
}
public String getAccessToken()
{
return accessToken;
}
public void setExpireIn(Long expireIn)
{
this.expireIn = expireIn;
}
public Long getExpireIn()
{
return expireIn;
}
public void setRefreshToken(String refreshToken)
{
this.refreshToken = refreshToken;
}
public String getRefreshToken()
{
return refreshToken;
}
public void setOpenId(String openId)
{
this.openId = openId;
}
public String getOpenId()
{
return openId;
}
public void setUid(String uid)
{
this.uid = uid;
}
public String getUid()
{
return uid;
}
public void setAccessCode(String accessCode)
{
this.accessCode = accessCode;
}
public String getAccessCode()
{
return accessCode;
}
public void setUnionId(String unionId)
{
this.unionId = unionId;
}
public String getUnionId()
{
return unionId;
}
public void setScope(String scope)
{
this.scope = scope;
}
public String getScope()
{
return scope;
}
public void setTokenType(String tokenType)
{
this.tokenType = tokenType;
}
public String getTokenType()
{
return tokenType;
}
public void setIdToken(String idToken)
{
this.idToken = idToken;
}
public String getIdToken()
{
return idToken;
}
public void setMacAlgorithm(String macAlgorithm)
{
this.macAlgorithm = macAlgorithm;
}
public String getMacAlgorithm()
{
return macAlgorithm;
}
public void setMacKey(String macKey)
{
this.macKey = macKey;
}
public String getMacKey()
{
return macKey;
}
public void setCode(String code)
{
this.code = code;
}
public String getCode()
{
return code;
}
public void setOauthToken(String oauthToken)
{
this.oauthToken = oauthToken;
}
public String getOauthToken()
{
return oauthToken;
}
public void setOauthTokenSecret(String oauthTokenSecret)
{
this.oauthTokenSecret = oauthTokenSecret;
}
public String getOauthTokenSecret()
{
return oauthTokenSecret;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("uuid", getUuid())
.append("userId", getUserId())
.append("source", getSource())
.append("accessToken", getAccessToken())
.append("expireIn", getExpireIn())
.append("refreshToken", getRefreshToken())
.append("openId", getOpenId())
.append("uid", getUid())
.append("accessCode", getAccessCode())
.append("unionId", getUnionId())
.append("scope", getScope())
.append("tokenType", getTokenType())
.append("idToken", getIdToken())
.append("macAlgorithm", getMacAlgorithm())
.append("macKey", getMacKey())
.append("code", getCode())
.append("oauthToken", getOauthToken())
.append("oauthTokenSecret", getOauthTokenSecret())
.toString();
}
}

View File

@ -0,0 +1,75 @@
package com.ruoyi.oauth.common.mapper;
import java.util.List;
import com.ruoyi.oauth.common.domain.OauthUser;
/**
* 第三方认证Mapper接口
*
* @author ruoyi
* @date 2024-01-18
*/
public interface OauthUserMapper {
/**
* 查询第三方认证
*
* @param id 第三方认证主键
* @return 第三方认证
*/
public OauthUser selectOauthUserById(Long id);
public OauthUser selectOauthUserByUserId(Long userId);
/**
* 查询第三方认证
* 钉钉抖音uuid 为用户的 unionid
* 微信公众平台登录京东酷家乐美团uuid 为用户的 openId
* 微信开放平台登录QQuuid 为用户的 openId平台支持获取unionid unionid AuthToken
* 如果支持在登录完成后可以通过 response.getData().getToken().getUnionId() 获取
* Googleuuid 为用户的 subsub为Google的所有账户体系中用户唯一的身份标识符详见OpenID Connect
*
* @param uuid
* @return
*/
public OauthUser selectOauthUserByUUID(String uuid);
/**
* 查询第三方认证列表
*
* @param oauthUser 第三方认证
* @return 第三方认证集合
*/
public List<OauthUser> selectOauthUserList(OauthUser oauthUser);
/**
* 新增第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
public int insertOauthUser(OauthUser oauthUser);
/**
* 修改第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
public int updateOauthUser(OauthUser oauthUser);
/**
* 删除第三方认证
*
* @param id 第三方认证主键
* @return 结果
*/
public int deleteOauthUserById(Long id);
/**
* 批量删除第三方认证
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteOauthUserByIds(Long[] ids);
}

View File

@ -0,0 +1,65 @@
package com.ruoyi.oauth.common.service;
import java.util.List;
import com.ruoyi.oauth.common.domain.OauthUser;
/**
* 第三方认证Service接口
*
* @author ruoyi
* @date 2024-01-18
*/
public interface IOauthUserService
{
/**
* 查询第三方认证
*
* @param id 第三方认证主键
* @return 第三方认证
*/
public OauthUser selectOauthUserById(Long id);
public OauthUser selectOauthUserByUUID(String uuid);
public OauthUser selectOauthUserByUserId(Long userId);
/**
* 查询第三方认证列表
*
* @param oauthUser 第三方认证
* @return 第三方认证集合
*/
public List<OauthUser> selectOauthUserList(OauthUser oauthUser);
/**
* 新增第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
public int insertOauthUser(OauthUser oauthUser);
/**
* 修改第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
public int updateOauthUser(OauthUser oauthUser);
/**
* 批量删除第三方认证
*
* @param ids 需要删除的第三方认证主键集合
* @return 结果
*/
public int deleteOauthUserByIds(Long[] ids);
/**
* 删除第三方认证信息
*
* @param id 第三方认证主键
* @return 结果
*/
public int deleteOauthUserById(Long id);
}

View File

@ -0,0 +1,104 @@
package com.ruoyi.oauth.common.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.oauth.common.domain.OauthUser;
import com.ruoyi.oauth.common.mapper.OauthUserMapper;
import com.ruoyi.oauth.common.service.IOauthUserService;
/**
* 第三方认证Service业务层处理
*
* @author ruoyi
* @date 2024-01-18
*/
@Service
public class OauthUserServiceImpl implements IOauthUserService
{
@Autowired
private OauthUserMapper oauthUserMapper;
/**
* 查询第三方认证
*
* @param id 第三方认证主键
* @return 第三方认证
*/
@Override
public OauthUser selectOauthUserById(Long id)
{
return oauthUserMapper.selectOauthUserById(id);
}
@Override
public OauthUser selectOauthUserByUUID(String uuid)
{
return oauthUserMapper.selectOauthUserByUUID(uuid);
}
@Override
public OauthUser selectOauthUserByUserId(Long userId)
{
return oauthUserMapper.selectOauthUserByUserId(userId);
}
/**
* 查询第三方认证列表
*
* @param oauthUser 第三方认证
* @return 第三方认证
*/
@Override
public List<OauthUser> selectOauthUserList(OauthUser oauthUser)
{
return oauthUserMapper.selectOauthUserList(oauthUser);
}
/**
* 新增第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
@Override
public int insertOauthUser(OauthUser oauthUser)
{
return oauthUserMapper.insertOauthUser(oauthUser);
}
/**
* 修改第三方认证
*
* @param oauthUser 第三方认证
* @return 结果
*/
@Override
public int updateOauthUser(OauthUser oauthUser)
{
return oauthUserMapper.updateOauthUser(oauthUser);
}
/**
* 批量删除第三方认证
*
* @param ids 需要删除的第三方认证主键
* @return 结果
*/
@Override
public int deleteOauthUserByIds(Long[] ids)
{
return oauthUserMapper.deleteOauthUserByIds(ids);
}
/**
* 删除第三方认证信息
*
* @param id 第三方认证主键
* @return 结果
*/
@Override
public int deleteOauthUserById(Long id)
{
return oauthUserMapper.deleteOauthUserById(id);
}
}

View File

@ -0,0 +1,153 @@
<?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="com.ruoyi.oauth.common.mapper.OauthUserMapper">
<resultMap type="OauthUser" id="OauthUserResult">
<result property="id" column="id" />
<result property="uuid" column="uuid" />
<result property="userId" column="user_id" />
<result property="source" column="source" />
<result property="accessToken" column="access_token" />
<result property="expireIn" column="expire_in" />
<result property="refreshToken" column="refresh_token" />
<result property="openId" column="open_id" />
<result property="uid" column="uid" />
<result property="accessCode" column="access_code" />
<result property="unionId" column="union_id" />
<result property="scope" column="scope" />
<result property="tokenType" column="token_type" />
<result property="idToken" column="id_token" />
<result property="macAlgorithm" column="mac_algorithm" />
<result property="macKey" column="mac_key" />
<result property="code" column="code" />
<result property="oauthToken" column="oauth_token" />
<result property="oauthTokenSecret" column="oauth_token_secret" />
</resultMap>
<sql id="selectOauthUserVo">
select id, uuid, user_id, source, access_token, expire_in, refresh_token, open_id, uid, access_code, union_id, scope, token_type, id_token, mac_algorithm, mac_key, code, oauth_token, oauth_token_secret from oauth_user
</sql>
<select id="selectOauthUserList" parameterType="OauthUser" resultMap="OauthUserResult">
<include refid="selectOauthUserVo"/>
<where>
<if test="uuid != null and uuid != ''"> and uuid = #{uuid}</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="source != null and source != ''"> and source = #{source}</if>
<if test="accessToken != null and accessToken != ''"> and access_token = #{accessToken}</if>
<if test="expireIn != null "> and expire_in = #{expireIn}</if>
<if test="refreshToken != null and refreshToken != ''"> and refresh_token = #{refreshToken}</if>
<if test="openId != null and openId != ''"> and open_id = #{openId}</if>
<if test="uid != null and uid != ''"> and uid = #{uid}</if>
<if test="accessCode != null and accessCode != ''"> and access_code = #{accessCode}</if>
<if test="unionId != null and unionId != ''"> and union_id = #{unionId}</if>
<if test="scope != null and scope != ''"> and scope = #{scope}</if>
<if test="tokenType != null and tokenType != ''"> and token_type = #{tokenType}</if>
<if test="idToken != null and idToken != ''"> and id_token = #{idToken}</if>
<if test="macAlgorithm != null and macAlgorithm != ''"> and mac_algorithm = #{macAlgorithm}</if>
<if test="macKey != null and macKey != ''"> and mac_key = #{macKey}</if>
<if test="code != null and code != ''"> and code = #{code}</if>
<if test="oauthToken != null and oauthToken != ''"> and oauth_token = #{oauthToken}</if>
<if test="oauthTokenSecret != null and oauthTokenSecret != ''"> and oauth_token_secret = #{oauthTokenSecret}</if>
</where>
</select>
<select id="selectOauthUserById" parameterType="Long" resultMap="OauthUserResult">
<include refid="selectOauthUserVo"/>
where oauth_user.id = #{id}
</select>
<select id="selectOauthUserByUserId" parameterType="Long" resultMap="OauthUserResult">
<include refid="selectOauthUserVo"/>
where oauth_user.user_id = #{user_id}
</select>
<select id="selectOauthUserByUUID" parameterType="String" resultMap="OauthUserResult">
<include refid="selectOauthUserVo"/>
where oauth_user.uuid = #{uuid}
</select>
<insert id="insertOauthUser" parameterType="OauthUser">
insert into oauth_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="uuid != null and uuid != ''">uuid,</if>
<if test="userId != null">user_id,</if>
<if test="source != null and source != ''">source,</if>
<if test="accessToken != null and accessToken != ''">access_token,</if>
<if test="expireIn != null">expire_in,</if>
<if test="refreshToken != null">refresh_token,</if>
<if test="openId != null">open_id,</if>
<if test="uid != null">uid,</if>
<if test="accessCode != null">access_code,</if>
<if test="unionId != null">union_id,</if>
<if test="scope != null">scope,</if>
<if test="tokenType != null">token_type,</if>
<if test="idToken != null">id_token,</if>
<if test="macAlgorithm != null">mac_algorithm,</if>
<if test="macKey != null">mac_key,</if>
<if test="code != null">code,</if>
<if test="oauthToken != null">oauth_token,</if>
<if test="oauthTokenSecret != null">oauth_token_secret,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="uuid != null and uuid != ''">#{uuid},</if>
<if test="userId != null">#{userId},</if>
<if test="source != null and source != ''">#{source},</if>
<if test="accessToken != null and accessToken != ''">#{accessToken},</if>
<if test="expireIn != null">#{expireIn},</if>
<if test="refreshToken != null">#{refreshToken},</if>
<if test="openId != null">#{openId},</if>
<if test="uid != null">#{uid},</if>
<if test="accessCode != null">#{accessCode},</if>
<if test="unionId != null">#{unionId},</if>
<if test="scope != null">#{scope},</if>
<if test="tokenType != null">#{tokenType},</if>
<if test="idToken != null">#{idToken},</if>
<if test="macAlgorithm != null">#{macAlgorithm},</if>
<if test="macKey != null">#{macKey},</if>
<if test="code != null">#{code},</if>
<if test="oauthToken != null">#{oauthToken},</if>
<if test="oauthTokenSecret != null">#{oauthTokenSecret},</if>
</trim>
</insert>
<update id="updateOauthUser" parameterType="OauthUser">
update oauth_user
<trim prefix="SET" suffixOverrides=",">
<if test="uuid != null and uuid != ''">uuid = #{uuid},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="source != null and source != ''">source = #{source},</if>
<if test="accessToken != null and accessToken != ''">access_token = #{accessToken},</if>
<if test="expireIn != null">expire_in = #{expireIn},</if>
<if test="refreshToken != null">refresh_token = #{refreshToken},</if>
<if test="openId != null">open_id = #{openId},</if>
<if test="uid != null">uid = #{uid},</if>
<if test="accessCode != null">access_code = #{accessCode},</if>
<if test="unionId != null">union_id = #{unionId},</if>
<if test="scope != null">scope = #{scope},</if>
<if test="tokenType != null">token_type = #{tokenType},</if>
<if test="idToken != null">id_token = #{idToken},</if>
<if test="macAlgorithm != null">mac_algorithm = #{macAlgorithm},</if>
<if test="macKey != null">mac_key = #{macKey},</if>
<if test="code != null">code = #{code},</if>
<if test="oauthToken != null">oauth_token = #{oauthToken},</if>
<if test="oauthTokenSecret != null">oauth_token_secret = #{oauthTokenSecret},</if>
</trim>
where oauth_user.id = #{id}
</update>
<delete id="deleteOauthUserById" parameterType="Long">
delete from oauth_user where id = #{id}
</delete>
<delete id="deleteOauthUserByIds" parameterType="String">
delete from oauth_user where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>

View File

@ -4,17 +4,17 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class WxH5Constant { public class WxPubConstant {
@Value("${wx.h5.appId}") @Value("${wx.pub.appId}")
private String appId; private String appId;
@Value("${wx.h5.appSecret}") @Value("${wx.pub.appSecret}")
private String appSecret; private String appSecret;
@Value("${wx.h5.url}") @Value("${wx.pub.url}")
private String url; private String url;
@Value("${wx.h5.open}") @Value("${wx.pub.open}")
private Boolean open; private Boolean open;
public String getUrl() { public String getUrl() {

View File

@ -1,40 +1,72 @@
package com.ruoyi.oauth.wx.controller; package com.ruoyi.oauth.wx.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous; import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.oauth.wx.constant.WxH5Constant; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oauth.common.domain.OauthUser;
import com.ruoyi.oauth.common.service.IOauthUserService;
import com.ruoyi.oauth.wx.constant.WxMiniAppConstant; import com.ruoyi.oauth.wx.constant.WxMiniAppConstant;
import com.ruoyi.oauth.wx.constant.WxPubConstant;
import com.ruoyi.oauth.wx.service.Impl.WxLoginServiceImpl; import com.ruoyi.oauth.wx.service.Impl.WxLoginServiceImpl;
@RestController @RestController
@RequestMapping("/wx") @RequestMapping("/wx")
public class WxLoginController extends BaseController { public class WxLoginController extends BaseController {
@Autowired @Autowired
public WxH5Constant wxH5AppConstant; public WxPubConstant wxH5AppConstant;
@Autowired @Autowired
public WxMiniAppConstant wxMiniAppConstant; public WxMiniAppConstant wxMiniAppConstant;
@Autowired @Autowired
WxLoginServiceImpl wxLoginServiceImpl; private WxLoginServiceImpl wxLoginServiceImpl;
@Autowired
private IOauthUserService oauthUserService;
@Anonymous @Anonymous
@GetMapping("/miniapp/{code}") @PostMapping("/login/{source}/{code}")
public AjaxResult loginMiniApp(@PathVariable("code") String code) { public AjaxResult loginMiniApp(@PathVariable("source") String source, @PathVariable("code") String code) {
return success(wxLoginServiceImpl.doLoginMiniApp(code)); String token = null;
AjaxResult ajax = AjaxResult.success();
if ("miniapp".equals(source))
token = wxLoginServiceImpl.doLoginMiniApp(code);
else if ("pub".equals(source)) {
token = wxLoginServiceImpl.doLoginPub(code);
} else {
return error("错误的登录方式");
}
ajax.put(Constants.TOKEN, token);
return ajax;
} }
@Anonymous @PostMapping("/register/{source}/{code}")
@GetMapping("/h5/{code}") public AjaxResult register(@PathVariable("source") String source, @PathVariable("code") String code) {
public AjaxResult loginH5App(@PathVariable("code") String code) { OauthUser oauthUser = oauthUserService.selectOauthUserByUserId(getUserId());
return success(wxLoginServiceImpl.doLoginMiniApp(code)); if (oauthUser != null) {
return error("不可以重复绑定");
} else {
String msg = "";
oauthUser = new OauthUser();
oauthUser.setUserId(getUserId());
oauthUser.setCode(code);
if ("miniapp".equals(source))
msg = wxLoginServiceImpl.doRegisterMiniApp(oauthUser);
else if ("pub".equals(source)) {
msg = wxLoginServiceImpl.doRegisterPub(oauthUser);
} else {
return error("错误的注册方式");
}
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
} }
} }

View File

@ -8,11 +8,19 @@ import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.oauth.common.domain.OauthUser;
import com.ruoyi.oauth.common.service.IOauthUserService;
import com.ruoyi.oauth.common.utils.HttpClientUtil; import com.ruoyi.oauth.common.utils.HttpClientUtil;
import com.ruoyi.oauth.wx.constant.WxH5Constant;
import com.ruoyi.oauth.wx.constant.WxMiniAppConstant; import com.ruoyi.oauth.wx.constant.WxMiniAppConstant;
import com.ruoyi.oauth.wx.constant.WxPubConstant;
import com.ruoyi.oauth.wx.service.WxLoginService; import com.ruoyi.oauth.wx.service.WxLoginService;
import com.ruoyi.system.service.ISysUserService;
@Service @Service
public class WxLoginServiceImpl implements WxLoginService { public class WxLoginServiceImpl implements WxLoginService {
@ -20,12 +28,20 @@ public class WxLoginServiceImpl implements WxLoginService {
private WxMiniAppConstant wxAppConstant; private WxMiniAppConstant wxAppConstant;
@Autowired @Autowired
private WxH5Constant wxH5Constant; private WxPubConstant wxH5Constant;
@Autowired @Autowired
private HttpClientUtil httpClientUtil; private HttpClientUtil httpClientUtil;
@Autowired
private TokenService tokenService;
@Autowired
private UserDetailsServiceImpl userDetailsServiceImpl;
@Autowired
private ISysUserService userService;
@Autowired
private IOauthUserService oauthUserService;
public Map<String, String> doLogin(String url, String appid, String secret, String code) { public Map<String, String> doAuth(String url, String appid, String secret, String code) {
String getMessageUrl = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code String getMessageUrl = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code
+ "&grant_type=authorization_code"; + "&grant_type=authorization_code";
String result = httpClientUtil.sendHttpGet(getMessageUrl); String result = httpClientUtil.sendHttpGet(getMessageUrl);
@ -44,22 +60,79 @@ public class WxLoginServiceImpl implements WxLoginService {
} }
} }
public String doLogin(String openid) {
OauthUser selectOauthUser = oauthUserService.selectOauthUserByUUID(openid);
if (selectOauthUser == null) {
return null;
}
SysUser sysUser = userService.selectUserById(selectOauthUser.getUserId());
if (sysUser == null) {
throw new ServiceException("该微信未绑定用户");
}
LoginUser loginUser = (LoginUser) userDetailsServiceImpl.createLoginUser(sysUser);
return tokenService.createToken(loginUser);
}
@Override @Override
public String doLoginH5(String code) { public String doLoginPub(String code) {
return doLogin( String openid = doAuth(
wxH5Constant.getUrl(), wxH5Constant.getUrl(),
wxH5Constant.getAppId(), wxH5Constant.getAppId(),
wxH5Constant.getAppSecret(), wxH5Constant.getAppSecret(),
code).get("openid"); code).get("openid");
return doLogin(openid);
} }
@Override @Override
public String doLoginMiniApp(String code) { public String doLoginMiniApp(String code) {
return doLogin( String openid = doAuth(
wxAppConstant.getUrl(), wxAppConstant.getUrl(),
wxAppConstant.getAppId(), wxAppConstant.getAppId(),
wxAppConstant.getAppSecret(), wxAppConstant.getAppSecret(),
code).get("openid"); code).get("openid");
return doLogin(openid);
}
@Override
public String doRegisterPub(OauthUser oauthUser) {
if (StringUtils.isEmpty(oauthUser.getCode())) {
return "没有凭证";
}
if (oauthUser.getUserId() == null) {
return "请先注册账号";
}
Map<String, String> doAuth = doAuth(
wxH5Constant.getUrl(),
wxH5Constant.getAppId(),
wxH5Constant.getAppSecret(),
oauthUser.getCode());
oauthUser.setOpenId(doAuth.get("openid"));
oauthUser.setUuid(doAuth.get("openid"));
oauthUser.setSource("WXPub");
oauthUser.setAccessToken(doAuth.get("sessionKey"));
oauthUserService.insertOauthUser(oauthUser);
return "";
}
@Override
public String doRegisterMiniApp(OauthUser oauthUser) {
if (StringUtils.isEmpty(oauthUser.getCode())) {
return "没有凭证";
}
if (oauthUser.getUserId() == null) {
return "请先注册账号";
}
Map<String, String> doAuth = doAuth(
wxAppConstant.getUrl(),
wxAppConstant.getAppId(),
wxAppConstant.getAppSecret(),
oauthUser.getCode());
oauthUser.setOpenId(doAuth.get("openid"));
oauthUser.setUuid(doAuth.get("openid"));
oauthUser.setSource("WXPub");
oauthUser.setAccessToken(doAuth.get("sessionKey"));
oauthUserService.insertOauthUser(oauthUser);
return "";
} }
} }

View File

@ -1,7 +1,14 @@
package com.ruoyi.oauth.wx.service; package com.ruoyi.oauth.wx.service;
import com.ruoyi.oauth.common.domain.OauthUser;
public interface WxLoginService { public interface WxLoginService {
public String doLoginMiniApp(String code); public String doLoginMiniApp(String code);
public String doLoginH5(String code); public String doLoginPub(String code);
public String doRegisterPub(OauthUser oauthUser);
public String doRegisterMiniApp(OauthUser oauthUser);
} }

View File

@ -20,3 +20,26 @@ CREATE TABLE oauth_user (
oauth_token VARCHAR(255) COMMENT 'Twitter平台用户的附带属性部分平台可能没有', oauth_token VARCHAR(255) COMMENT 'Twitter平台用户的附带属性部分平台可能没有',
oauth_token_secret VARCHAR(255) COMMENT 'Twitter平台用户的附带属性部分平台可能没有' oauth_token_secret VARCHAR(255) COMMENT 'Twitter平台用户的附带属性部分平台可能没有'
); );
-- 菜单 SQL
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证', '1', '1', 'oauth', 'system/oauth/index', 1, 0, 'C', '0', '0', 'system:oauth:list', '#', 'admin', sysdate(), '', null, '第三方认证菜单');
-- 按钮父菜单ID
SELECT @parentId := LAST_INSERT_ID();
-- 按钮 SQL
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证查询', @parentId, '1', '#', '', 1, 0, 'F', '0', '0', 'system:oauth:query', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证新增', @parentId, '2', '#', '', 1, 0, 'F', '0', '0', 'system:oauth:add', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证修改', @parentId, '3', '#', '', 1, 0, 'F', '0', '0', 'system:oauth:edit', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证删除', @parentId, '4', '#', '', 1, 0, 'F', '0', '0', 'system:oauth:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('第三方认证导出', @parentId, '5', '#', '', 1, 0, 'F', '0', '0', 'system:oauth:export', '#', 'admin', sysdate(), '', null, '');