What is OAuth2 in REST API: Simple Explanation and Example
OAuth2 is a secure way for REST APIs to allow users or apps to access resources without sharing passwords. It works by issuing tokens that grant limited access, keeping user data safe.How It Works
Imagine you want to let a friend borrow your car, but only for a short trip and without giving them your house keys. OAuth2 works similarly for REST APIs. Instead of sharing your password, you give a special ticket called a token that lets the friend use the car for a limited time and purpose.
When a user logs into an app, the app asks an authorization server for permission. If the user agrees, the server gives the app a token. The app then uses this token to access the REST API on behalf of the user. The API checks the token to make sure it’s valid and what it allows before giving access.
This way, the user’s password stays private, and the app only gets the access it needs, improving security and control.
Example
This example shows how a REST API might check an OAuth2 token sent in a request header to allow access.
from flask import Flask, request, jsonify app = Flask(__name__) # A fake token for demonstration VALID_TOKENS = {"abc123": "user1"} @app.route('/data') def data(): auth_header = request.headers.get('Authorization') if not auth_header or not auth_header.startswith('Bearer '): return jsonify({"error": "Missing or invalid token"}), 401 token = auth_header.split()[1] if token not in VALID_TOKENS: return jsonify({"error": "Invalid token"}), 403 user = VALID_TOKENS[token] return jsonify({"message": f"Hello, {user}! Here is your protected data."}) if __name__ == '__main__': app.run(debug=True)
When to Use
Use OAuth2 in REST APIs when you want to let users or apps access data securely without sharing passwords. It is perfect for:
- Third-party apps accessing user data (like social media or cloud storage)
- Mobile apps needing limited access to a user’s account
- APIs that require different levels of access for different users
OAuth2 helps protect user privacy and reduces risks if tokens are stolen, since tokens can be limited and revoked easily.
Key Points
- OAuth2 uses tokens instead of passwords for safer access.
- Tokens have limited permissions and time to reduce risk.
- It separates the roles of authorization server and resource server.
- Commonly used for user login and third-party app access.