1 # Copyright (C) 2022 Wind River Systems, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 from werkzeug.wrappers import Request, Response
16 from o2common.helper import o2logging
17 from o2common.authmw.authprov import auth_definer
19 logger = o2logging.get_logger(__name__)
22 class AuthRequiredExp(Exception):
23 def __init__(self, value):
28 'WWW-Authenticate': '{}'.format(self.value)}
31 class AuthFailureExp(Exception):
32 def __init__(self, value):
37 'WWW-Authenticate': '{}'.format(self.value)}
40 def _response_wrapper(environ, start_response, header):
41 res = Response(headers=header,
42 mimetype='text/plain', status=401)
43 return res(environ, start_response)
46 def _internal_err_response_wrapper(environ, start_response):
47 res = Response(mimetype='text/plain', status=500)
48 return res(environ, start_response)
51 class authmiddleware():
57 def __init__(self, app):
60 def __call__(self, environ, start_response):
61 logger.info(__name__ + 'authentication middleware')
62 req = Request(environ, populate_request=True, shallow=True)
64 auth_header = req.headers.get('Authorization', None)
66 auth_token = auth_header.split(" ")[1]
68 ad = auth_definer('oauth')
69 # invoke underlying auth mdw to make k8s/keystone api
70 ret = ad.authenticate(auth_token)
73 "auth success with oauth token: " + auth_token)
75 return self.app(environ, start_response)
76 except Exception as ex:
78 'Internal exception happend \
79 ed {}'.format(str(ex)), exc_info=True)
81 _internal_err_response_wrapper(environ,
85 'Bearer realm="Authentication Failed"')
87 raise AuthRequiredExp('Bearer realm="Authentication Required"')
88 except AuthRequiredExp as ex:
89 return _response_wrapper(environ, start_response, ex.dictize())
90 except AuthFailureExp as ex:
91 return _response_wrapper(environ, start_response, ex.dictize())
92 except Exception as ex:
93 logger.error('Internal exception happended {}'.format(
94 str(ex)), exc_info=True)
95 return _internal_err_response_wrapper(environ, start_response)