Understanding OAuth 2.0: Secure Authorization for Web Apps

OAuth 2.0 is the industry standard for delegated authorization. It lets users grant third-party access without sharing passwords.

## Key Concepts

- **Resource Owner**: The user
- **Client**: The application requesting access
- **Authorization Server**: Issues tokens
- **Resource Server**: Hosts protected data

## Authorization Code Flow

```
1. User clicks "Login with Google"
2. Redirect to: /authorize?response_type=code&client_id=xxx&redirect_uri=xxx
3. User grants permission
4. Redirect back with: ?code=AUTH_CODE
5. Server exchanges code for token
6. Use access token for API calls
```

## Implementation (Node.js)

```javascript
// Step 1: Redirect to authorization
app.get('/login', (req, res) => {
 const url = `https://accounts.google.com/o/oauth2/v2/auth?
   client_id=${CLIENT_ID}&
   redirect_uri=${REDIRECT_URI}&
   response_type=code&
   scope=profile email`;
 res.redirect(url);
});

// Step 2: Handle callback
app.get('/callback', async (req, res) => {
 const { code } = req.query;
 const response = await fetch('https://oauth2.googleapis.com/token', {
   method: 'POST',
   body: JSON.stringify({
     code, client_id: CLIENT_ID, client_secret: SECRET,
     redirect_uri: REDIRECT_URI, grant_type: 'authorization_code'
   })
 });
 const { access_token } = await response.json();
});
```

## Token Types

- **Access Token**: Short-lived, used for API calls
- **Refresh Token**: Long-lived, used to get new access tokens

## JWT (JSON Web Tokens)

```javascript
const jwt = require('jsonwebtoken');

// Create token
const token = jwt.sign({ userId: 123 }, SECRET, { expiresIn: '1h' });

// Verify token
const decoded = jwt.verify(token, SECRET);
```

## Best Practices

1. Always use HTTPS
2. Store tokens in HTTP-only cookies
3. Validate tokens server-side
4. Use short expiration times
5. Implement token revocation

## Conclusion

OAuth 2.0 with JWT is the backbone of modern authentication. Use established libraries instead of implementing from scratch.

评论
暂无评论