MCPcopy Create free account
hub / github.com/authlib/authlib / ResourceProtector

Class ResourceProtector

authlib/integrations/flask_oauth2/resource_protector.py:18–115  ·  view source on GitHub ↗

A protecting method for resource servers. Creating a ``require_oauth`` decorator easily with ResourceProtector:: from authlib.integrations.flask_oauth2 import ResourceProtector require_oauth = ResourceProtector() # add bearer token validator from authlib.oauth2

Source from the content-addressed store, hash-verified

16
17
18class ResourceProtector(_ResourceProtector):
19 """A protecting method for resource servers. Creating a ``require_oauth``
20 decorator easily with ResourceProtector::
21
22 from authlib.integrations.flask_oauth2 import ResourceProtector
23
24 require_oauth = ResourceProtector()
25
26 # add bearer token validator
27 from authlib.oauth2.rfc6750 import BearerTokenValidator
28 from project.models import Token
29
30
31 class MyBearerTokenValidator(BearerTokenValidator):
32 def authenticate_token(self, token_string):
33 return Token.query.filter_by(access_token=token_string).first()
34
35
36 require_oauth.register_token_validator(MyBearerTokenValidator())
37
38 # protect resource with require_oauth
39
40
41 @app.route("/user")
42 @require_oauth(["profile"])
43 def user_profile():
44 user = User.get(current_token.user_id)
45 return jsonify(user.to_dict())
46
47 """
48
49 def raise_error_response(self, error):
50 """Raise HTTPException for OAuth2Error. Developers can re-implement
51 this method to customize the error response.
52
53 :param error: OAuth2Error
54 :raise: HTTPException
55 """
56 status = error.status_code
57 body = json.dumps(dict(error.get_body()))
58 headers = error.get_headers()
59 raise_http_exception(status, body, headers)
60
61 def acquire_token(self, scopes=None, **kwargs):
62 """A method to acquire current valid token with the given scope.
63
64 :param scopes: a list of scope values
65 :return: token object
66 """
67 request = FlaskJsonRequest(_req)
68 # backward compatibility
69 kwargs["scopes"] = scopes
70 for claim in kwargs:
71 if isinstance(kwargs[claim], str):
72 kwargs[claim] = [kwargs[claim]]
73 token = self.validate_request(request=request, **kwargs)
74 token_authenticated.send(self, token=token)
75 g.authlib_server_oauth2_token = token

Callers 3

serverFunction · 0.90
resource_serverFunction · 0.90
resource_protectorFunction · 0.90

Calls

no outgoing calls

Tested by 3

serverFunction · 0.72
resource_serverFunction · 0.72
resource_protectorFunction · 0.72