Created
November 30, 2023 16:53
-
-
Save ikasoba/4cb175a79e7a329f1aff1bf20702abb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { nanoid } from "https://esm.sh/nanoid/"; | |
import { encodeBase64 } from "https://deno.land/std/encoding/base64.ts"; | |
const base64uri = (data: ArrayBuffer) => | |
encodeBase64(data) | |
.replaceAll("+", "-") | |
.replaceAll("/", "_") | |
.replaceAll("=", ""); | |
const clientId = "https://ikasoba.github.io/misskey-oauth2-client-example"; | |
const redirectUri = | |
"https://ikasoba.github.io/misskey-oauth2-client-example/redirect"; | |
const codeChallengeMethod = "S256"; | |
const codeVerifier = nanoid(); | |
const codeChallenge = base64uri( | |
await crypto.subtle.digest("sha-256", new TextEncoder().encode(codeVerifier)) | |
); | |
const host = new URL("https://misskey.systems"); | |
const meta = await fetch( | |
new URL("/.well-known/oauth-authorization-server", host) | |
).then((res) => res.json()); | |
const authRequest = new URL(meta.authorization_endpoint, host); | |
authRequest.searchParams.set("response_type", "code"); | |
authRequest.searchParams.set("client_id", clientId); | |
authRequest.searchParams.set("redirect_uri", redirectUri); | |
authRequest.searchParams.set("code_challenge", codeChallenge); | |
authRequest.searchParams.set("code_challenge_method", codeChallengeMethod); | |
authRequest.searchParams.set("scope", "write:notes"); | |
console.log("ブラウザでリクエスト", authRequest.toString()); | |
const code = prompt("認可コードを入力")!; | |
const tokenResponse = await fetch(new URL(meta.token_endpoint, host), { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/x-www-form-urlencoded", | |
}, | |
body: new URLSearchParams({ | |
grant_type: "authorization_code", | |
code: code, | |
client_id: clientId, | |
redirect_uri: redirectUri, | |
code_verifier: codeVerifier, | |
}).toString(), | |
}).then((res) => res.json()); | |
const token = tokenResponse.access_token; | |
await fetch(new URL("/api/notes/create", host), { | |
method: "POST", | |
headers: { | |
Authorization: `Bearer ${token}`, | |
"Content-Type": "application/json", | |
}, | |
body: JSON.stringify({ | |
text: "OAuth2.0 テスト", | |
}), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment