1、背景
第三方通過鏈接訪問若依項目,該鏈接通過攜帶唯一標識符:phone(手機號),項目通過手機號查詢本項目數據庫人員信息實現模擬登錄。
2、實現
2.1. 前端實現
2.1.1?創建專用模擬登錄頁面PhoneLogin.vue
<template><div class="phone-login-container"><div v-if="loading">正在登錄中...</div><div v-if="error" class="error-message">{{ error }}</div></div>
</template><script>
import { simulateLogin } from '@/api/login'
import { removeToken, setToken } from '@/utils/auth'export default {name: 'PhoneLogin',data() {return {loading: true,error: ''}},created() {this.handlePhoneLogin()},methods: {async handlePhoneLogin() {// 先清除舊賬號的所有信息await this.$store.dispatch('LogOut')removeToken()const phone = this.$route.query.phoneif (!phone) {this.error = '請提供手機號參數'this.loading = falsereturn}try {// 發起模擬登錄請求const response = await simulateLogin(phone)const token = response.data.tokenif (!token) {throw new Error('未能獲取有效token')}// 存儲新tokensetToken(token)// 獲取新用戶信息await this.$store.dispatch('GetInfo')// 清除可能的路由緩存this.$router.app.$options.router.matcher = this.$router.app.$options.router.matcher// 跳轉到首頁this.$router.push({ path: '/' })} catch (error) {console.error('手機號登錄失敗:', error)this.error = '登錄失敗: ' + (error.message || '未知錯誤')this.loading = false}}}
}
</script>
2.1.2?添加模擬登錄API
?在?api/login.js
?中添加:
// 模擬登錄API
export function simulateLogin(phone) {return request({url: '/auth/simulate-login?phone'+phone,method: 'get'});
}
2.1.3?添加白名單
src/permission.js中添加:
const whiteList = ['/login', '/register',"/phoneLogin"]
2.1.4 添加路由
在router/index.js中添加跳轉路由
{path: '/phoneLogin',component: () => import('@/views/stationRule/phoneLogin'),hidden: true,meta: {title: '手機號登錄',noAuth: true // 關鍵!設置為不需要認證}},
2.1.5?修改全局權限控制
在?src/permission.js
?中確保允許訪問該路由:
router.beforeEach(async (to, from, next) => {// 獲取tokenconst hasToken = getToken()// 如果是phoneLogin路由,直接放行if (to.path === '/phoneLogin') {next()return}// ...原有其他邏輯
}
2.2后端實現?
2.2.1在?ruoyi-admin
?模塊中創建控制器SimulateAuthController
@RestController
@RequestMapping("/auth")
public class SimulateAuthController extends BaseController {@Autowiredprivate ISimulateLoginService simulateLoginService;@Autowiredprivate TokenService tokenService;@GetMapping("/simulate-login")public AjaxResult simulateLogin(@RequestParam("phone") String phone, HttpServletRequest request) {if (StringUtils.isEmpty(phone)) {return AjaxResult.error("手機號不能為空");}// 使舊token失效String oldToken = tokenService.getToken(request);if (StringUtils.isNotEmpty(oldToken)) {tokenService.delLoginUser(oldToken);}return simulateLoginService.simulateLoginByPhone(phone);}
}
2.2.1創建服務接口和實現?
public interface ISimulateLoginService {AjaxResult simulateLoginByPhone(String phone);
}@Service
public class SimulateLoginServiceImpl implements ISimulateLoginService {@Autowiredprivate TokenService tokenService;@Overridepublic AjaxResult simulateLoginByPhone(String phone) {// 根據user數據庫查詢用戶,在UserMapper中添加查詢方法SysUser user = sysUserMapper.selectUserByPhone(phone);if (user == null) {return AjaxResult.error("用戶不存在");}// 創建tokenLoginUser loginUser = new LoginUser();loginUser.setUser(user);loginUser.setPermissions(permissionService.getMenuPermission(user));loginUser.setRoles(roleService.selectRoleKeys(user.getUserId()));String token = tokenService.createToken(loginUser);// 返回token和用戶信息Map<String, Object> result = new HashMap<>();result.put("token", token);result.put("user", user);return AjaxResult.success(result);}
}
3. 安全配置
3.1 添加白名單
在?SecurityConfig.java
?中添加模擬登錄接口到白名單:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity// ...其他配置.authorizeRequests()// 放行模擬登錄接口.antMatchers("/auth/simulate-login").anonymous()// ...其他放行配置
}
4.訪問?
直接訪問?http://localhost:8080?phone=13800138000
成功跳轉并可以訪問其他鏈接