get token and add minimock

This commit is contained in:
kekskurse 2024-09-13 23:41:29 +02:00
parent 2e7e4630af
commit 38929a7201
8 changed files with 122 additions and 10 deletions

50
auth.go
View file

@ -92,11 +92,57 @@ func (a Auth) GetAuthorizationURL(state string) (string, error) {
}
func (a Auth) GetTokenFromCode(code string) (Token, error) {
t := Token{}
form := url.Values{}
form.Add("grant_type", "authorization_code")
form.Add("code", code)
req, err := http.NewRequest("POST", a.authConfig.TokenEndpoint, strings.NewReader(form.Encode()))
if err != nil {
return Token{}, fmt.Errorf("%w: %q", ErrCantCreateTokenRequests, err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(a.clientConfig.ClientID, a.clientConfig.ClientSecret)
hc := http.Client{}
resp, err := hc.Do(req)
if err != nil {
return Token{}, fmt.Errorf("%w: %q", ErrCantSendRequestsForToken, err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return Token{}, fmt.Errorf("%w: %q", ErrCantSendRequestsForToken, err)
}
fmt.Println(string(body))
fmt.Println(resp.StatusCode)
if resp.StatusCode != 200 {
var er struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
err = json.Unmarshal(body, &er)
if err != nil {
return Token{}, fmt.Errorf("%w: %s", ErrWrongResponseFromServer, string(body))
}
if er.ErrorDescription != "" {
return Token{}, fmt.Errorf("%w: %s", ErrWrongResponseFromServer, er.ErrorDescription)
}
return Token{}, fmt.Errorf("%w: %s", ErrWrongResponseFromServer, string(body))
}
t := Token{}
t.CreatedAt = time.Now()
err = json.Unmarshal(body, &t)
if err != nil {
return Token{}, fmt.Errorf("%w: %q", ErrCantGetTokenForCode, err)
}
return t, nil
}

View file

@ -79,16 +79,64 @@ func TestGetAuthorizationUrl(t *testing.T) {
}
}
func TestUseCodeToGetToken(t *testing.T) {
tts := []struct {
name string
tokenURL string
token string
ExptError error
ExptErrorString string
ExptAccessToken string
}{
{
name: "token-to-old",
tokenURL: "http://localhost:8084//token/wrong-code",
ExptError: ErrWrongResponseFromServer,
ExptErrorString: "cant get access token from server: The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client",
},
{
name: "valide-token",
tokenURL: "http://localhost:8084//token/valide-access-token.json",
ExptAccessToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ5ZGRiNmI0YzAxMmEyNjE2NWVhZDY5NTc5YWU1MWE5IiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2F1dGgua2Vrcy5jbG91ZC9hcHBsaWNhdGlvbi9vL3Rlc3QvIiwic3ViIjoiNTE5NGYyZTViNmRlOGEwOTQxODEwM2FkY2ZkYzM0NTMzZjAxYWNjM2Q5YzIwZDM5NzZiNzI1YjE3MmFhMmE0MyIsImF1ZCI6ImhUcUVGcjBDeVMzWFZXWUMwZm9sblpsVTM0SmRqcFJRbWpweWhyUVIiLCJleHAiOjE3MjYyNjMwODEsImlhdCI6MTcyNjI2Mjc4MSwiYXV0aF90aW1lIjoxNzI0NDAzMjczLCJhY3IiOiJnb2F1dGhlbnRpay5pby9wcm92aWRlcnMvb2F1dGgyL2RlZmF1bHQiLCJlbWFpbCI6InNvZXJlbkBzaWVnaXNtdW5kLXBvc2NobWFubi5ldSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJuYW1lIjoiU1x1MDBmNnJlbiIsImdpdmVuX25hbWUiOiJTXHUwMGY2cmVuIiwicHJlZmVycmVkX3VzZXJuYW1lIjoia2Vrc2t1cnNlIiwibmlja25hbWUiOiJrZWtza3Vyc2UiLCJncm91cHMiOlsiYXV0aGVudGlrIEFkbWlucyIsIk5leHRjbG91ZCIsImdpdHVzZXIiLCJnaXRhZG1pbiJdLCJhenAiOiJoVHFFRnIwQ3lTM1hWV1lDMGZvbG5abFUzNEpkanBSUW1qcHloclFSIiwidWlkIjoibDdCY3dsM3k2S1dBVVdJS2NoRjZVbHFDS3hkM1UxTlpxVHJRdjZHaSJ9.CSma-ZI9Sw3G9MuJlgnNUR7mmr-twYjf0hKpm7Z745oICIxIT-9A1rcOzN7goX9J_PeRABxBD3fCuOX0F1Xw3qZqs115zvllKl4R9Gs8zkk17Rdrubb7FWpbcz0NHpZPnv_d20zeHG9tIDmlg_Z_p-4AzOs5rvhrc0Dw_AMwnON8rWCIzB9XEq9z74ZDveCywdPzoW29Z1sVZQp5rwaFacMOPan1ERZNv5DAg4cR3znPszkgboW80XVCn7IYYnIWTHG70n3CkimVXgTBEO6PzwShejrv1_ggZrD01_K6OwCivTCEVJBZm_ElpnTgzyPwENnfacnuCnOoZK0dXTnOw-K9ZXQ8uEVbVpMK_F4ETnLs20ZHi-VJeU2IgQu84k8k1fx-jvwkvJbHpfrTL75Ajga8VAdcQHbqfNwppFsQwLRIocp_Ay5YpkBRS1Z3lWvA8XcI3V3O9pe836Jx2P4Q7YTnEFdVxTrqBCbwO2DjabO1fElbuokdf-qS46pFE-_wEwtTOfGUxXrH7NeI2vYwEYReKhO0Thf3iUfTtJbGVPphAvmHRNP2LBcpUeShQGBKHi4FtBPdTPvlGULCn8k9SZ3TTZXAzsE2uYfvf7sVjvEvD1jwLpDL8hZW6Ceqs-0KvY_CB3W2n2HbzGWHKgAL-4DPVRPHI_pEfGH0RnaTJ0M",
},
{
name: "server-retrun-500-error",
tokenURL: "http://localhost:8084//token/invalide-response",
ExptError: ErrWrongResponseFromServer,
ExptErrorString: "cant get access token from server: somethings was really wrong",
},
}
for _, tt := range tts {
t.Run(tt.name, func(t *testing.T) {
ClientConfig := ClientConfig{ClientID: "abc", ClientSecret: "def", RedirectURL: "http://localhost/something"}
AuthConfig := AuthConfig{TokenEndpoint: tt.tokenURL}
client, err := NewAuthWithConfig(ClientConfig, AuthConfig)
assert.Nil(t, err, "should be abel to create client without error")
token, err := client.GetTokenFromCode("abc")
if tt.ExptError != nil {
assert.ErrorIs(t, err, tt.ExptError, "should return right error")
assert.Equal(t, tt.ExptErrorString, err.Error(), "should return currect error string")
return
}
assert.Nil(t, err, "should be abled to get token without error")
assert.Equal(t, tt.ExptAccessToken, token.AccessToken, "should return access token")
})
}
}
func TestAuthenticLogin(t *testing.T) {
t.Skip("dev test")
clientConfig := ClientConfig{ClientID: "abc", ClientSecret: "def"}
clientConfig := ClientConfig{ClientID: "abc", ClientSecret: "abc", RedirectURL: "http://localhost/somethingelse"}
client, err := NewAuthWithConfigurationURL(clientConfig, "http://localhost:8084/openid-configuration")
assert.Nil(t, err, "should be able to create client without error")
url, err := client.GetAuthorizationURL("")
assert.Nil(t, err, "should be able to create url without error")
fmt.Println(url)
token, err := client.GetTokenFromCode("e34bc2c7840e4386b17880dd1142c67b")
token, err := client.GetTokenFromCode("9aa96340040342e5a7df969834d9e278")
assert.Nil(t, err, "should be able to get code without error")
fmt.Println(token)
}

View file

@ -1,7 +1,7 @@
services:
oAuthDummyServer:
image: nginx
miniMock:
image: kekskurse/minimock
volumes:
- ./static/openid-configuration:/usr/share/nginx/html/openid-configuration
- ./minimock:/data/
ports:
- 8084:80
- 8084:3333

View file

@ -5,4 +5,8 @@ import "errors"
var (
ErrCantGetConfiguratorData = errors.New("cant get data from configurator url")
ErrCantGetAuthorizationURL = errors.New("cant get url to recirect user to")
ErrCantCreateTokenRequests = errors.New("cant create requesats to get token with code")
ErrCantSendRequestsForToken = errors.New("cant send requests for token with code")
ErrCantGetTokenForCode = errors.New("cant get oauth token with code")
ErrWrongResponseFromServer = errors.New("cant get access token from server")
)

12
minimock/config.yml Normal file
View file

@ -0,0 +1,12 @@
---
routen:
- path: /openid-configuration
response_file: /data/openid-configuration
- path: /token/wrong-code
response_file: /data/token/wrong-code.json
response_http_status: 400
- path: /token/valide-access-token.json
response_file: /data/token/valide-access-token.json
- path: /token/invalide-response
response_body: somethings was really wrong
response_http_status: 500

View file

@ -0,0 +1 @@
{"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ5ZGRiNmI0YzAxMmEyNjE2NWVhZDY5NTc5YWU1MWE5IiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRw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3VzZXJuYW1lIjoia2Vrc2t1cnNlIiwibmlja25hbWUiOiJrZWtza3Vyc2UiLCJncm91cHMiOlsiYXV0aGVudGlrIEFkbWlucyIsIk5leHRjbG91ZCIsImdpdHVzZXIiLCJnaXRhZG1pbiJdfQ.SHaeGciIEprvKr1d-tboJXvF3pYoTKsQ6LkL1TPakS0847Rzmx6NmhN64na0A8kTRPQfCNdF6YTgjRuZBJQpZO3T6ck2tS_c7SgqGohXSOx2aAm6Ny11zA7PkjTtWnuMgayfH8EASDqe55U-h61E1lratHz79ykBovee4rAn-EccWkH2KQARypF34DI18mIcuLLC08EzyqLj4dux85RWGRg7PX57KGPi_effuw6ndjgBfJskvOY2K7HAobEGxJgBIC3fPJe5iCamZgCg2q-PCr1FfEWpgDtVLhHc-m1wWsj-nUGI64yfulK2LYQp8sHBXsVHoXy60ACq6wICJlttXxTjFh9W6iCMjmybPE83CquK8bUff19pHXQygjKPqzAL58REh8HDu1mgdI3fWkLPnjkWziA6zEmjTCS_Aj4lSYxehZXeBN1nyE3UwHSLWlbCQC_204J_zEXjTfKEFHEdRClmX_BO6MPD9pHYcdKNWRxXatRmuyQ5GiwK1J9W625SKmoMypz8rkvIm-E7SLRxfYaJTS6-bDd9-cPO5jF6LFRejivfsbcIbLRDZKS3oV3dbagEfoX6g4wyiz7d290fVWB4wpzS3nQIkZzcmW_QD4UhKnd7wzkQIz88WRqfMwOJrfML_Lg17F55JpGENjczPAK48YC3BguSsTCX_rAiCTk"}

View file

@ -0,0 +1 @@
{"error": "invalid_grant", "error_description": "The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client"}