Deno
A Deno server handling requests with Cloud Auth looks like this.
Verifier
An authenticateRequest
function that validates an incoming web standard request can be implemented in src/authenticate.ts
like this:
ts
import { createVerifier } from 'npm:@featherscloud/auth@^0.6.2'
const appId = '<your-app-id>'
const verifier = createVerifier({ appId })
/**
* Verify authentication for a web standard request object.
* Will throw an error if verification was not successful.
*
* @param request The request object
* @returns The authentication information like `user` and `token`
*/
export async function authenticateRequest(request: Request) {
const header = request.headers.get('Authorization')
return verifier.verifyHeader(header!)
}
Server
A Deno server can then use it in src/server.ts
like this:
ts
import { authenticateRequest } from "./authenticate.ts"
const port = 3030
// Headers for handling CORS
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Origin': '*',
}
async function handler(request: Request): Promise<Response> {
// Get the path from the request object
const url = new URL(request.url);
const path = url.pathname;
try {
// Handle CORS preflight request
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 200,
headers,
})
}
else if (path === '/message') {
const { user } = await authenticateRequest(request)
const body = {
message: `Hello ${user.email} from Deno!`,
}
return Response.json(body, {
status: 200,
headers,
})
} else {
throw new Error(`Not Found ${path}`)
}
}
catch (error) {
return Response.json({ error: error.message }, {
status: 400,
headers,
})
}
}
console.log(`Deno application listening on http://localhost:3030`)
Deno.serve({ port }, handler)
The full Deno example can be found here.