HTTP Basic Authentication Policy¶
To adopt basic HTTP authentication, you can use Pyramid's built-in authentication policy, pyramid.authentication.BasicAuthAuthenticationPolicy
.
This is a complete working example with very simple authentication and authorization:
1from pyramid.authentication import BasicAuthAuthenticationPolicy
2from pyramid.authorization import ACLAuthorizationPolicy
3from pyramid.config import Configurator
4from pyramid.httpexceptions import HTTPForbidden
5from pyramid.httpexceptions import HTTPUnauthorized
6from pyramid.security import ALL_PERMISSIONS
7from pyramid.security import Allow
8from pyramid.security import Authenticated
9from pyramid.security import forget
10from pyramid.view import forbidden_view_config
11from pyramid.view import view_config
12
13@view_config(route_name='home', renderer='json', permission='view')
14def home_view(request):
15 return {
16 'page': 'home',
17 'userid': request.authenticated_userid,
18 'principals': request.effective_principals,
19 'context_type': str(type(request.context)),
20 }
21
22@forbidden_view_config()
23def forbidden_view(request):
24 if request.authenticated_userid is None:
25 response = HTTPUnauthorized()
26 response.headers.update(forget(request))
27
28 # user is logged in but doesn't have permissions, reject wholesale
29 else:
30 response = HTTPForbidden()
31 return response
32
33def check_credentials(username, password, request):
34 if username == 'admin' and password == 'admin':
35 # an empty list is enough to indicate logged-in... watch how this
36 # affects the principals returned in the home view if you want to
37 # expand ACLs later
38 return []
39
40class Root:
41 # dead simple, give everyone who is logged in any permission
42 # (see the home_view for an example permission)
43 __acl__ = (
44 (Allow, Authenticated, ALL_PERMISSIONS),
45 )
46
47def main(global_conf, **settings):
48 config = Configurator(settings=settings)
49
50 authn_policy = BasicAuthAuthenticationPolicy(check_credentials)
51 config.set_authentication_policy(authn_policy)
52 config.set_authorization_policy(ACLAuthorizationPolicy())
53 config.set_root_factory(lambda request: Root())
54
55 config.add_route('home', '/')
56
57 config.scan(__name__)
58 return config.make_wsgi_app()
59
60if __name__ == '__main__':
61 from waitress import serve
62 app = main({})
63 serve(app, listen='localhost:8000')