Tauri 插件 OAuth 设备
在桌面上处理基于浏览器的 OAuth 流的最小化 Rust 库和 Tauri 插件 应用。 此插件将生成一个临时本地主机服务器, 以捕获 OAuth 重定向, 解析 使用桌面应用程序 OAuth 的挑战.
为什么是这个插件?
许多OAuth供应商(如Google和GitHub)不允许自定义的URI计划("深链接")作为 重定向 URL 。 此插件提供了一个解决方案 :
- 复制临时本地服务器
- 抓取 OAuth 重定向
- 将授权数据传送回您的应用程序
说明: 关于采用深层联系的替代办法, 见 tauri-plugin-深链路. 深层联系 如果没有打开实例, 插件可以自动启动您的应用程序 .
安装
# Cargo.toml
[dependencies]
tauri-plugin-oauth = "2"
对于使用 npm 或 纱线的 Tauri 项目 :
npm install @fabianlars/tauri-plugin-oauth@2
# or
yarn add @fabianlars/tauri-plugin-oauth@2
使用量
锈
use tauri::{command, Emitter, Window};
use tauri_plugin_oauth::start;
#[command]
async fn start_server(window: Window) -> Result<u16, String> {
start(move |url| {
// Because of the unprotected localhost port, you must verify the URL here.
// Preferebly send back only the token, or nothing at all if you can handle everything else in Rust.
let _ = window.emit("redirect_uri", url);
})
.map_err(|err| err.to_string())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_oauth::init())
.invoke_handler(tauri::generate_handler![start_server])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
类型脚本
import {
start,
cancel,
onUrl,
onInvalidUrl,
} from "@fabianlars/tauri-plugin-oauth";
async function startOAuthFlow() {
try {
const port = await start();
console.log(`OAuth server started on port ${port}`);
// Set up listeners for OAuth results
await onUrl((url) => {
console.log("Received OAuth URL:", url);
// Handle the OAuth redirect
});
// Initiate your OAuth flow here
// ...
} catch (error) {
console.error("Error starting OAuth server:", error);
}
}
// Don't forget to stop the server when you're done
async function stopOAuthServer() {
try {
await cancel(port);
console.log("OAuth server stopped");
} catch (error) {
console.error("Error stopping OAuth server:", error);
}
}
配置
您可以使用 OauthConfig 结构 :
use tauri_plugin_oauth::OauthConfig;
let config = OauthConfig {
ports: Some(vec![8000, 8001, 8002]),
response: Some("OAuth process completed. You can close this window.".into()),
..Default::default()
};
start_with_config(config, |url| {
// Handle OAuth URL
})
.expect("Failed to start OAuth server");
回调后重定向浏览器
如果你设定 redirect_uri 字段中,插件将以一个
302 Found 用于该 URL 而不是服务 HTML 响应。 这是有用的,当你想要
浏览器, 一旦供应商被击中, 即可登陆您的应用程序的真实页面( 例如 Tauri 窗口 URL)
本地主机服务器.
let config = OauthConfig {
redirect_uri: Some("http://tauri.localhost/oauth/done".into()),
..Default::default()
};
说明: 何时
redirect_uri设置, 处理器关闭接收本地主机 URL 供应商击出( 例如 ).http://127.0.0.1:<port>/?code=...&state=...(b) —— 没有 完整 URL 带有 碎片(#...),只有浏览器看到。 如果您的 OAuth 流量返回一个符号 URL 片段( 暗流), 剖析window.location并转发 返回您的应用程序; 默认值( 无)redirect_uri) 行为使用内线 脚本已经为你做了这个.
安全考虑
- 总是在您服务器侧验证收到的 OAuth URL , 然后再认为它是真实的 .
- 在 OAuth 流中使用 HTTPS 来防止中层人的攻击 .
- 在您的应用程序中执行适当的代号存储并刷新机制 .
捐款
总是欢迎捐款! 请随意提交拉力请求.
许可证
这个项目根据下列任何一种许可证持有双重许可证,可自行选择: