User Authentication —HTTP Basic Auth

George Chang
Jul 24, 2017 · 5 min read

網站的使用者認證是一個流程,去驗證使用者的身份。

最常見的作法就是利用帳號密碼去通過驗證登入網站,例如在一個購物網站成功登入後可以查看/管理你的個人訂單。

上述的作法就是透過Login form + Session的使用者登入,不過我們往後再介紹。

要介紹的是HTTP基本認證 (HTTP Basic Auth),這個認證是基於對網站請求(request)時的一種驗證方式,也就是說我跟你要東西的時候要先喊聲口令表明身分。

傳輸的格式為user:password,轉成base64編碼後傳輸。

登入時會在HTTP Header加入一個Authorization字段如下:

Authorization: Basic cm9iaW46aXNjaGFybWluZw==

在”Basic後面那串就是針對帳號密碼的base64字串。

然後我們來用python console還原看看:

$ python
>>> import base64
>>> base64.b64decode('cm9iaW46aXNjaGFybWluZw==').decode('utf-8')
'robin:ischarming'

便可以看到還原的帳號密碼是什麼。

由此可知,當網站非使用HTTPS傳輸時,這些請求可以被輕易得知,那麼有心人士便可以還原登入的帳號密碼。

HTTP Basic Auth唯一的優點是它的設計很簡單,而且所有的瀏覽器都支援,因此可以用在私人或保證安全的連線中。

接著讓我們來看看如何用Flask實作HTTP Basic Auth,我們依然使用之前的restful-flask project來改寫。

例如像之前實作的/users 使用者清單,一般的網站不會大方的讓大家看到所有的使用者,這便是一個需要使用者登入認證的例子。

讓我們在app/views/users.py加入一些程式碼:

# app/views/users.py# 引用Flask的request and Response object
from flask import request, Response
# 加入check_auth function,用來檢查帳號密碼
def check_auth(username, password):
return username == 'robin' and password == 'ischarming'
# 加入authenticate function,用來回應使用者需要通過認證才可以瀏覽,返回401 status code
def authenticate():
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
# 把上面的方法包成一個裝飾器(decorator)
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated

可以看到在decorator內做了什麼事,我們從request object取得authorization的資料,如果使用者沒有尚未驗證,並且在輸入的帳號密碼不正確或未輸入,便會回傳authenticate()的內容。

@users.route('/', methods=['GET'])
@requires_auth
def index():
users = User.query.all()
return render_template('users/index.html', users = users)

接著我們在/users這個route的方法直接加上decorator,便完成了HTTP Basic Auth的防護。

接著我們執行看看

$ python manage.py runserver
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

然後我們在瀏覽器輸入http://127.0.0.1:5000/users

便會跳出如下圖視窗要求輸入帳號密碼。

最後附上githutb連結供參考,謝謝。

下一篇會介紹的是如何用一開始提的Login form + Session來實作使用者登入。

origino

A Technical Organization in Taiwan

George Chang

Written by

Software Engineer

origino

origino

A Technical Organization in Taiwan

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade