爱发电 OAuth 登录 SDK for Remix

目录

概要

爱发电 OAuth 文档: https://afdian.net/p/010ff078177211eca44f52540025c377

注意一下这里有两个细节:

  1. 这里的 OAuth 非标准化 OAuth,没有 AccessToken
  2. 申请和维护没有管理界面,需要给管理员发送私信

代码仓库: https://github.com/willin/remix-auth-afdian

在线演示: https://remix-auth-afdian.willin.wang/

安装使用

包名: remix-auth-afdian

bash 复制代码
npm i --save remix-auth-afdian
# or
pnpm i remix-auth-afdian
# or
yarn add remix-auth-afdian

配置 Remix Auth

在项目根目录下创建一个 auth.server.ts 代码文件:

ts 复制代码
import { createCookieSessionStorage, type ActionFunctionArgs } from '@remix-run/cloudflare';
import { Authenticator } from 'remix-auth';
import { AfdianStrategy } from 'remix-auth-afdian/build/index';

export function getAuthenticator({ context, request }: ActionFunctionArgs) {
  const url = new URL(request.url);
  url.pathname = '/auth/afdian/callback';
  const sessionStorage = createCookieSessionStorage({
    cookie: {
      name: 'sid',
      httpOnly: true,
      secure: context.env.CF_PAGES === 'production',
      sameSite: 'lax',
      path: '/',
      secrets: ['s3cr3t']
    }
  });

  const authenticator = new Authenticator(sessionStorage, {
    throwOnError: true
  });

  const afdianStrategy = new AfdianStrategy(
    {
      clientID: context.env.AFDIAN_CLIENT_ID,
      clientSecret: context.env.AFDIAN_CLIENT_SECRET,
      callbackURL: url.toString()
    },
    async ({ accessToken, extraParams, profile }) => {
      return profile;
    }
  );
  authenticator.use(afdianStrategy);
  return authenticator;
}

替换其中的配置,如:

  • @remix-run/cloudflare 根据需要,切换 Remix 运行环境
  • callback url 回调的地址
  • session 配置
  • client 相关信息,id 及密钥

配置登录跳转

创建 auth.afdian.tsx 文件:

ts 复制代码
import { type ActionFunctionArgs, redirect } from "@remix-run/cloudflare";
import { getAuthenticator } from "~/auth.server";

export async function loader() {
  return redirect("/");
}

export async function action(args: ActionFunctionArgs) {
  const authenticator = getAuthenticator(args);
  return await authenticator.authenticate("afdian", args.request, {
    successRedirect: "/dashboard",
  });

}

注意:该文件命名采用的是 remix v2 规则,v1 的话用目录分隔。

配置 callback 回调

创建 auth.afdian.callback.tsx 文件:

ts 复制代码
import { getAuthenticator } from '~/auth.server';

export async function loader(args) {
  const authenticator = getAuthenticator(args);

  return authenticator.authenticate('afdian', args.request, {
    successRedirect: '/dashboard',
    failureRedirect: '/'
  });
}

这样已经大功告成了。

配置 Demo 测试页

比如这里叫 dashboard.tsx 页面:

ts 复制代码
import { json, redirect } from '@remix-run/cloudflare';
import { Form, useLoaderData } from '@remix-run/react';
import { getAuthenticator } from '~/auth.server';

export async function loader(args) {
  const authenticator = getAuthenticator(args);

  const user = await authenticator.isAuthenticated(args.request);
  if (!user) {
    throw redirect('/');
  }

  return json(user);
}

export default function Page() {
  const data = useLoaderData<typeof loader>();

  return (
    <div>
      <h1>已登录 Logged in</h1>
      <p>
        <Form action='/api/logout' method='POST'>
          <button>Logout</button>
        </Form>
      </p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

配置注销登录

ts 复制代码
import { type LoaderFunction, type ActionFunction, redirect } from '@remix-run/cloudflare';
import { getAuthenticator } from '~/auth.server';

export const loader: LoaderFunction = () => {
  return redirect('/');
};

export const action: ActionFunction = async (args) => {
  const { request } = args;
  const authenticator = getAuthenticator(args);
  const referer = request.headers.get('referer');
  const returnPath = referer ? new URL(referer).pathname : '/';
  return await authenticator.logout(request, {
    redirectTo: returnPath
  });
};

这个可以根据需要添加。

如果您对爱发电感兴趣,想要让其支持更多的框架。可以联系我进行定制开发。

打赏地址:https://afdian.net/a/willin

感谢您的观看~

相关推荐
布莱克6053 小时前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
djjjx.4 小时前
Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
布莱克6055 小时前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
Rabitebla6 小时前
【Linux】文件篇(五):手撕简易 FILE——模拟实现 C 标准 I/O 缓冲机制
linux·服务器·c语言·笔记·学习·ubuntu
FRing038 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng18 小时前
组件化服务端渲染模式SSR
前端
CoderYanger8 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
whitelbwwww9 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃9 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
MSTcheng.9 小时前
【MySQL】MySQL数据库——表的操作
数据库·mysql·adb