Subscribed unsubscribe Subscribe Subscribe

Google App Engine でBasic認証を実装 改

Python GoogleAppEngine

Google App Engine でBasic認証を実装 - すぎゃーんメモから少し改良してみた。

# -*- coding: utf-8 -*-

import logging
from base64 import b64decode
from google.appengine.ext import webapp

class BasicAuthentication(webapp.RequestHandler):
    def __init__(self):
        logging.getLogger().setLevel(logging.DEBUG)

    def get(self):
        # Basic認証
        if self.__basicAuth():
            self.response.out.write('認証されたよ!')
        else:
            code = 401
            self.error(code)
            self.response.out.write(self.response.http_status_message(code))
            
    def __basicAuth(self):
        auth_header = self.request.headers.get('Authorization')
        if auth_header:
            try:
                (scheme, base64) = auth_header.split(' ')
                if scheme != 'Basic':
                    return False
                (username, password) = b64decode(base64).split(':')
                # 認証
                if username == 'hoge' and password == 'fuga':
                    return True
            except (ValueError, TypeError), err:
                logging.warn(type(err))
                return False

        self.response.set_status(401)
        self.response.headers['WWW-Authenticate'] = 'Basic realm="BasicTest"'