RuoYi-Vue集成第三方登录:OAuth2.0与微信登录
你是否还在为系统接入第三方登录而烦恼?本文将详细介绍如何在RuoYi-Vue权限管理系统中集成OAuth2.0与微信登录,让用户通过微信一键登录系统,提升用户体验。读完本文,你将掌握第三方登录的配置步骤、核心代码实现以及前后端交互流程。
第三方登录架构设计
RuoYi-Vue作为基于SpringBoot和Vue的前后端分离权限管理系统,其登录流程核心围绕LoginUser模型展开。该模型存储用户认证信息、权限集合和登录状态,是实现第三方登录的基础数据结构。
核心登录逻辑位于SysLoginController的login方法,通过接收用户名密码生成JWT令牌。为支持第三方登录,需扩展该流程,新增OAuth2.0认证端点和微信登录回调处理。
OAuth2.0集成准备
1. 添加依赖
在pom.xml中添加Spring Security OAuth2依赖,用于处理OAuth2.0协议交互:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
2. 扩展用户模型
修改LoginUser类,新增第三方登录相关字段,如开放平台ID、登录类型等:
ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUser.java
// 新增第三方登录字段
private String openId; // 第三方平台唯一标识
private String loginType; // 登录类型:password/wechat/oauth2
private String unionId; // 微信UnionID(多平台统一标识)
微信登录实现步骤
1. 微信开放平台配置
登录微信开放平台注册应用,获取以下参数:
- AppID:wx1234567890abcdef
- AppSecret:a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
- 回调域名:https://your-domain.com/wechat/callback
2. 后端回调接口开发
在SysLoginController中新增微信登录回调处理接口:
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java
/**
* 微信登录回调处理
*/
@GetMapping("/wechat/callback")
public String wechatCallback(@RequestParam String code) {
// 1. 通过code获取access_token
String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=wx1234567890abcdef" +
"&secret=a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" +
"&code=" + code +
"&grant_type=authorization_code";
// 2. 解析返回结果获取openid
String result = restTemplate.getForObject(tokenUrl, String.class);
JSONObject json = JSONObject.parseObject(result);
String openId = json.getString("openid");
// 3. 查询或创建系统用户
SysUser user = userService.selectUserByOpenId(openId);
if (user == null) {
user = createUserByWechat(json); // 自动注册新用户
}
// 4. 生成系统令牌
LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
loginUser.setOpenId(openId);
loginUser.setLoginType("wechat");
String token = tokenService.createToken(loginUser);
// 5. 重定向到前端并携带令牌
return "redirect:/#/login?token=" + token;
}
3. 前端登录按钮集成
在登录页面login.vue添加微信登录按钮,使用微信图标:
<template>
<div class="login-container">
<!-- 原有账号密码登录表单 -->
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
<!-- 表单内容省略 -->
</el-form>
<!-- 微信登录按钮 -->
<div class="third-login">
<el-button
type="primary"
icon="wechat"
class="wechat-btn"
@click="handleWechatLogin"
>
<svg-icon icon-class="wechat" class="icon-wechat" />
微信快捷登录
</el-button>
</div>
</div>
</template>
<script>
export default {
methods: {
handleWechatLogin() {
// 构造微信授权链接
const appid = "wx1234567890abcdef";
const redirectUri = encodeURIComponent("https://your-domain.com/wechat/callback");
const authUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_login#wechat_redirect`;
// 打开微信扫码窗口
window.open(authUrl, "_self");
}
}
};
</script>
<style>
.icon-wechat {
width: 20px;
height: 20px;
margin-right: 5px;
}
.wechat-btn {
background-color: #07C160;
border-color: #07C160;
margin-top: 15px;
width: 100%;
}
</style>
微信图标来自项目内置SVG资源:ruoyi-ui/src/assets/icons/svg/wechat.svg
OAuth2.0通用登录流程
1. 认证服务器配置
创建OAuth2认证服务器配置类,支持多种第三方登录:
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("wechat")
.secret(passwordEncoder.encode("wechat-secret"))
.authorizedGrantTypes("authorization_code")
.scopes("snsapi_login")
.redirectUris("https://your-domain.com/wechat/callback");
}
}
2. 登录状态管理
修改TokenService的令牌生成逻辑,支持第三方登录类型:
public String createToken(LoginUser loginUser) {
// 设置登录类型(密码/微信/OAuth2)
claims.put("loginType", loginUser.getLoginType());
if (StringUtils.isNotEmpty(loginUser.getOpenId())) {
claims.put("openId", loginUser.getOpenId());
}
return Jwts.builder()
.setClaims(claims)
.setSubject(loginUser.getUsername())
.setIssuedAt(new Date())
.setExpiration(expireTime)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
安全与权限控制
1. 账号绑定策略
在用户中心实现第三方账号绑定功能,关联本地账号与微信OpenID:
ruoyi-ui/src/views/system/user/profile/index.vue
<el-form-item label="微信绑定">
<el-button
type="primary"
@click="bindWechat"
:disabled="user.wechatBind"
>
<svg-icon icon-class="wechat" class="icon-wechat" />
{{ user.wechatBind ? '已绑定' : '绑定微信账号' }}
</el-button>
</el-form-item>
2. 登录日志记录
扩展登录日志表,记录第三方登录信息:
-- SQL文件位置:[sql/ry_20250522.sql](https://link.gitcode.com/i/9e93183289391f4f5e8ac71f1eb9187e)
ALTER TABLE sys_login_log ADD COLUMN login_type VARCHAR(20) COMMENT '登录类型:password/wechat/oauth2';
ALTER TABLE sys_login_log ADD COLUMN open_id VARCHAR(64) COMMENT '第三方开放平台ID';
部署与测试
1. 配置参数说明
所有第三方登录参数集中配置在系统设置表:
ruoyi-ui/src/views/system/config/index.vue
| 参数键 | 说明 | 示例值 |
|---|---|---|
| sys.wechat.appid | 微信应用ID | wx1234567890abcdef |
| sys.wechat.secret | 微信应用密钥 | a1b2c3d4e5f6a7b8c9d0 |
| sys.oauth2.enabled | 是否启用OAuth2登录 | true |
2. 测试流程
- 访问系统登录页,点击"微信快捷登录"按钮
- 扫描弹出的微信二维码并确认授权
- 系统自动完成用户创建/登录,跳转至首页
- 在个人资料页可查看/管理已绑定的第三方账号
总结与展望
通过本文的实现方案,RuoYi-Vue系统已具备微信登录能力。该方案基于OAuth2.0标准协议,可灵活扩展支持QQ、微博等其他第三方平台。后续可优化以下方向:
- 实现账号安全等级判断,对第三方登录用户进行二次验证
- 开发移动端APP的微信SDK登录集成
- 添加登录方式统计分析,在监控面板展示第三方登录占比
官方环境使用手册:doc/若依环境使用手册.docx
点赞收藏本文,关注作者获取更多RuoYi-Vue实战教程,下期将带来"基于Redis的分布式Session实现"。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考




