1. Register Application
Create an application in your developer portal to obtain client credentials.
// OAuth 2.0 Authentication
const config = {
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_SECRET'
};
// Refresh token flow
async function getAccessToken() {
const response = await fetch('https://api.example.com/auth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(config.clientId + ':' + config.clientSecret)
},
body: 'grant_type=client_credentials'
});
const data = await response.json();
return data.access_token;
}
2. Use Access Token
Add the Bearer token to API requests for secure access.
// Use API with authentication
async function fetchData() {
const token = await getAccessToken();
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.json();
}
Security Best Practice
- Store credentials in environment variables
- Rotate secrets regularly
- Use refresh tokens for long sessions