0
0
Rest APIprogramming~5 mins

401 Unauthorized vs 403 Forbidden in Rest API

Choose your learning style9 modes available
Introduction

These two codes tell you why a web request was blocked. They help you understand if you need to log in or if you just can't access something.

When a user tries to access a page without logging in.
When a user is logged in but tries to open a page they don't have permission for.
When an API request is made without a valid token.
When a user tries to access admin features but is not an admin.
Syntax
Rest API
HTTP/1.1 401 Unauthorized
HTTP/1.1 403 Forbidden

401 Unauthorized means you must log in or provide valid credentials.

403 Forbidden means you are logged in but not allowed to access this resource.

Examples
This response asks the user to provide login details.
Rest API
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Access to the site"
This response tells the user they cannot access the page even if logged in.
Rest API
HTTP/1.1 403 Forbidden
Content-Type: text/html

<html><body><h1>Access Denied</h1></body></html>
Sample Program

This small web app checks if you send a token. If you send no token, it returns 401. If you send a wrong token, it returns 403. If the token is correct, it shows a secret message.

Rest API
from flask import Flask, request, abort

app = Flask(__name__)

@app.route('/secret')
def secret():
    auth = request.headers.get('Authorization')
    if not auth:
        abort(401)  # No login info
    if auth != 'Bearer validtoken':
        abort(403)  # Logged in but no permission
    return 'Welcome to the secret area!'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

401 means "You need to prove who you are".

403 means "I know who you are, but you can't do this".

Always use these codes correctly to help users and developers understand access problems.

Summary

401 Unauthorized means no or bad login info.

403 Forbidden means logged in but no permission.

Use these codes to guide users on what to do next.