Coverage for gws-app/gws/plugin/auth_method/token/__init__.py: 0%
44 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
1"""HTTP Token authorisation method.
3The token authorization works by passing a token in an HTTP header.
4For example, with this configuration::
6 auth.methods+ {
7 type "token"
8 header "X-My-Auth"
9 prefix "Bearer"
11 }
13the application would expect a header like ``X-My-Auth: Bearer <token>``, extract the token value
14and pass it along to authorization providers.
15"""
17import gws
18import gws.base.auth
19import gws.base.web
22gws.ext.new.authMethod('token')
25class Config(gws.base.auth.method.Config):
26 """HTTP-token authorization options (added in 8.1)"""
28 header: str
29 """HTTP header name"""
30 prefix: str = ''
31 """token prefix"""
34class Object(gws.base.auth.method.Object):
35 header: str
36 prefix: str
38 def configure(self):
39 self.uid = 'gws.plugin.auth_method.token'
40 self.header = self.cfg('header')
41 self.prefix = self.cfg('prefix', default='')
42 self.register_middleware(self.uid, depends_on=['auth'])
44 ##
46 def enter_middleware(self, req):
47 pass
49 def exit_middleware(self, req, res):
50 pass
52 def open_session(self, req):
53 am = self.root.app.authMgr
54 credentials = self._parse_header(req)
55 if not credentials:
56 return
57 user = am.authenticate(self, credentials)
58 if user:
59 user.authToken = credentials.get('token')
60 return am.sessionMgr.create(self, user)
62 def close_session(self, req, res):
63 pass
65 def _parse_header(self, req: gws.WebRequester):
66 h = req.header(self.header)
67 if not h:
68 return
70 a = h.strip().split()
72 if self.prefix:
73 if len(a) != 2 or a[0].lower() != self.prefix.lower():
74 return
75 return gws.Data(token=a[1])
76 else:
77 if len(a) != 1:
78 return
79 return gws.Data(token=a[0])