Authentication
Gokv provides an authentication middleware and storage, which can help you easily build a web application with a user system.
Currently, gokv supports the following providers:
Note that we plan to add support for email/password and other OAuth providers in the future.
Example
The following example shows how to use gokv authentication in a Deno http server.
Try it out online: https://dash.deno.com/playground/gokv-auth-example
import { serve } from "https://deno.land/std@0.160.0/http/server.ts";
import gokv from "https://deno.land/x/gokv@0.0.23/mod.ts";
const auth = gokv.Auth({
github: {
clientId: Deno.env.get("GITHUB_CLIENT_ID"),
clientSecret: Deno.env.get("GITHUB_CLIENT_SECRET"),
},
google: {
clientId: Deno.env.get("GOOGLE_CLIENT_ID"),
clientSecret: Deno.env.get("GOOGLE_CLIENT_SECRET"),
redirectUrl: "http://localhost:8000/oauth",
}
})
serve((req) => {
const url = new URL(req.url);
switch (url.pathname) {
case "/oauth":
return auth.callback(req);
case "/login":
return auth.login(req);
case "/logout":
return auth.logout(req);
default: {
const session = await auth(req)
if (session) {
return new Response(`Logined as ${session.user.name}`);
}
return new Response("Please login");
}
}
});
In this example, we added three special routes for authentication:
- OAuth callback:
/oauth
(this is theredirect_url
of OAuth providers) - Login with Github:
/login?provider=github&redirectUrl=/
- Login with Google:
/login?provider=google&redirectUrl=/
- Logout:
/logout?redirectUrl=/
Note that you can drop the
redirectUrl
query parameter and redirect to "/" after login/logout.