Coverage for gws-app/gws/plugin/auth_method/token/__init__.py: 0%
39 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 22:59 +0200
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 22:59 +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"""
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='')
43 ##
45 def open_session(self, req):
46 am = self.root.app.authMgr
47 credentials = self._parse_header(req)
48 if not credentials:
49 return
50 user = am.authenticate(self, credentials)
51 if user:
52 user.authToken = credentials.get('token')
53 return am.sessionMgr.create(self, user)
55 def close_session(self, req, res):
56 pass
58 def _parse_header(self, req: gws.WebRequester):
59 h = req.header(self.header)
60 if not h:
61 return
63 a = h.strip().split()
65 if self.prefix:
66 if len(a) != 2 or a[0].lower() != self.prefix.lower():
67 return
68 return gws.Data(token=a[1])
69 else:
70 if len(a) != 1:
71 return
72 return gws.Data(token=a[0])