Token Authentication
Token authentication allows you to manually set authentication state using JWT tokens. This is useful for implementing custom authentication flows or integrating with external authentication systems.
Basic Usage
The context API provides a simple method for token authentication:
api.signInWithToken(token)
Implementation Example
Here's an example of implementing token authentication:
<script server>
let error = null
if (request.method === 'POST') {
try {
const { token } = body()
signInWithToken(token)
redirect('/')
} catch (e) {
error = e.message
}
}
</script>
<mark>(...objs) => {
const s = prepare(objs);
$app.logger().error(s);
}</mark>
<form method="post">
<input name="token" type="text" placeholder="Enter JWT token" />
<button type="submit">Sign In</button>
</form>
API Reference
signInWithToken()
signInWithToken(token: string): void
The signInWithToken()
method:
- Sets the
pb_auth
cookie with the provided token - Does not validate the token
- Returns void
Cookie Behavior
PocketPages stores the authentication token in a cookie named pb_auth
. This cookie:
- Is automatically included in subsequent requests
- Is readable by both server and client-side code
- Can be cleared by setting an empty value
- Has no explicit expiration (session cookie)
Common Use Cases
API Integration
<script server>
// Obtain token from external API
const response = await fetch('https://api.example.com/auth', {
method: 'POST',
body: JSON.stringify(credentials)
})
const { token } = await response.json()
// Set the token
signInWithToken(token)
</script>
Custom Authentication Flow
<script server>
// Your custom auth logic
const user = await authenticateUser(credentials)
const token = generateToken(user)
// Set the token
signInWithToken(token)
</script>
Token Clearing
<script server>
// Clear the auth token
signInWithToken('')
// Or use signOut() which does the same thing
signOut()
</script>
Security Considerations
- Always transmit tokens over HTTPS
- Validate tokens on the server side
- Use appropriate token expiration times
- Consider implementing token refresh flows
- Be cautious with token storage in client-side code
Best Practices
- Use short-lived tokens
- Implement proper token validation
- Handle token expiration gracefully
- Consider implementing refresh tokens
- Log authentication events for security monitoring