Mercurial > gemma
comparison pkg/soap/oauth.go @ 5610:a826d84485c8 erdms2
Use token server to fetch token for ERDMS requests.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Mon, 31 Oct 2022 19:05:28 +0100 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
5609:e1936db6db8e | 5610:a826d84485c8 |
---|---|
1 // This is Free Software under GNU Affero General Public License v >= 3.0 | |
2 // without warranty, see README.md and license for details. | |
3 // | |
4 // SPDX-License-Identifier: AGPL-3.0-or-later | |
5 // License-Filename: LICENSES/AGPL-3.0.txt | |
6 // | |
7 // Copyright (C) 2022 by via donau | |
8 // – Österreichische Wasserstraßen-Gesellschaft mbH | |
9 // Software engineering by Intevation GmbH | |
10 // | |
11 // Author(s): | |
12 // * Sascha L. Teichmann <sascha.teichmann@intevation.de> | |
13 | |
14 package soap | |
15 | |
16 import ( | |
17 "encoding/base64" | |
18 "encoding/json" | |
19 "fmt" | |
20 "net/http" | |
21 "strings" | |
22 ) | |
23 | |
24 type Token struct { | |
25 AccessToken string `json:"access_token"` | |
26 Scope string `json:"scope"` | |
27 TokenType string `json:"token_type"` | |
28 ExpiresIn int `json:"expires_in"` | |
29 } | |
30 | |
31 func (token *Token) AddAuth(request *http.Request) { | |
32 request.Header.Add("Authorization", "Bearer "+token.AccessToken) | |
33 } | |
34 | |
35 func FetchToken(tokenURL, key, secret string) (*Token, error) { | |
36 | |
37 keyPair := key + ":" + secret | |
38 | |
39 encodedKeyPair := base64.URLEncoding.EncodeToString([]byte(keyPair)) | |
40 | |
41 req, err := http.NewRequest( | |
42 http.MethodPost, | |
43 tokenURL, | |
44 strings.NewReader("grant_type=client_credentials")) | |
45 | |
46 if err != nil { | |
47 return nil, err | |
48 } | |
49 | |
50 req.Header.Set("Authorization", "Basic "+encodedKeyPair) | |
51 | |
52 resp, err := http.DefaultClient.Do(req) | |
53 if err != nil { | |
54 return nil, err | |
55 } | |
56 | |
57 if resp.StatusCode != http.StatusOK { | |
58 return nil, fmt.Errorf( | |
59 "POST failed: %s (%d)", | |
60 http.StatusText(resp.StatusCode), | |
61 resp.StatusCode) | |
62 } | |
63 | |
64 var token Token | |
65 defer resp.Body.Close() | |
66 | |
67 if err = json.NewDecoder(resp.Body).Decode(&token); err != nil { | |
68 return nil, err | |
69 } | |
70 return &token, err | |
71 } |