|
9 | 9 |
|
10 | 10 | from insightconnect_plugin_runtime.exceptions import PluginException
|
11 | 11 |
|
| 12 | +from icon_servicenow.util.error_messages import MISSING_CREDENTIALS |
| 13 | + |
12 | 14 |
|
13 | 15 | class BearerAuth(AuthBase):
|
14 | 16 | """
|
@@ -132,15 +134,36 @@ def get_attachment(connection, sys_id):
|
132 | 134 | return str(base64.b64encode(result), "utf-8")
|
133 | 135 |
|
134 | 136 | def _get_oauth_token(self) -> str:
|
| 137 | + """ |
| 138 | + Sends a POST request to an OAuth server, automatically determining 'grant_password' |
| 139 | +
|
| 140 | + - If `username` and `password` are provided, grant_type = 'password' |
| 141 | + - If `username` and `password` are not provided, grant_type = 'client_credentials' |
| 142 | + """ |
| 143 | + |
| 144 | + if not self.client_id and not self.client_secret: |
| 145 | + raise PluginException(status_code=400, cause=MISSING_CREDENTIALS) |
| 146 | + |
| 147 | + # Automatic grant_type detection |
| 148 | + if self.username and self.password: |
| 149 | + grant_type = "password" |
| 150 | + else: |
| 151 | + grant_type = "client_credentials" |
| 152 | + |
| 153 | + # Building the payload |
| 154 | + payload = { |
| 155 | + "grant_type": grant_type, |
| 156 | + "client_id": self.client_id, |
| 157 | + "client_secret": self.client_secret, |
| 158 | + } |
| 159 | + |
| 160 | + if grant_type == "password": |
| 161 | + payload["username"] = self.username |
| 162 | + payload["password"] = self.password |
| 163 | + |
135 | 164 | response = requests.post(
|
136 | 165 | url=f"{self.base_url}oauth_token.do",
|
137 |
| - data={ |
138 |
| - "grant_type": "password", |
139 |
| - "client_id": self.client_id, |
140 |
| - "client_secret": self.client_secret, |
141 |
| - "username": self.username, |
142 |
| - "password": self.password, |
143 |
| - }, |
| 166 | + data=payload, |
144 | 167 | timeout=30,
|
145 | 168 | )
|
146 | 169 |
|
|
0 commit comments