def setUp(self): app = Sanic(__name__) app.config["SECRET_KEY"] = "my secret" app.config["CORS_AUTOMATIC_OPTIONS"] = True CORS(app) token_auth = HTTPTokenAuth("MyToken") @token_auth.verify_token def verify_token(token): return token == "this-is-the-token!" @token_auth.error_handler def error_handler(request): return text("error", status=401, headers={"WWW-Authenticate": 'MyToken realm="Foo"'}) @app.route("/") def index(request): return text("index") @app.route("/protected") @token_auth.login_required def token_auth_route(request): return text("token_auth") self.app = app self.token_auth = token_auth self.client = app.test_client
def setUp(self): app = Sanic(__name__) app.config["SECRET_KEY"] = "my secret" basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth("MyToken") multi_auth = MultiAuth(basic_auth, token_auth) @basic_auth.verify_password def verify_password(username, password): return username == "john" and password == "hello" @token_auth.verify_token def verify_token(token): return token == "this-is-the-token!" @token_auth.error_handler def error_handler(request): return text("error", status=401, headers={"WWW-Authenticate": 'MyToken realm="Foo"'}) @app.route("/") def index(request): return text("index") @app.route("/protected") @multi_auth.login_required def auth_route(request): return text("access granted") self.app = app self.client = app.test_client
def test_token_auth_login_invalid_no_callback(self): token_auth2 = HTTPTokenAuth("Token", realm="foo") @self.app.route("/protected2") @token_auth2.login_required def token_auth_route2(request): return text("token_auth2") rq, response = self.client.get( "/protected2", headers={"Authorization": "Token this-is-the-token!"}) self.assertEqual(response.status, 401) self.assertTrue("WWW-Authenticate" in response.headers) self.assertEqual(response.headers["WWW-Authenticate"], 'Token realm="foo"')
The root URL for this application can be accessed via basic auth, providing username and password, or via token auth, providing a bearer JWS token. """ import hashlib from sanic import Sanic, response from sanic_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth from itsdangerous import TimedJSONWebSignatureSerializer as JWS app = Sanic(__name__) app.config["SECRET_KEY"] = "top secret!" jws = JWS(app.config["SECRET_KEY"], expires_in=3600) basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth("Bearer") multi_auth = MultiAuth(basic_auth, token_auth) def hash_password(salt, password): salted = password + salt return hashlib.sha512(salted.encode("utf8")).hexdigest() app_salt = "APP_SECRET - don't do this in production" users = { "john": hash_password(app_salt, "hello"), "susan": hash_password(app_salt, "bye"), } for user in users.keys():