2023-01-13 15:22:03 +00:00
|
|
|
package application
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2023-02-06 19:26:43 +00:00
|
|
|
"io"
|
2023-01-13 15:22:03 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type TokenResponse struct {
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
IDToken string `json:"id_token"`
|
|
|
|
}
|
|
|
|
|
2023-02-07 21:50:49 +00:00
|
|
|
const JWTUsername = "goauthentik.io/token"
|
|
|
|
|
2023-01-13 15:22:03 +00:00
|
|
|
func (a *Application) attemptBasicAuth(username, password string) *Claims {
|
2023-02-07 21:50:49 +00:00
|
|
|
if username == JWTUsername {
|
|
|
|
res := a.attemptBearerAuth(password)
|
|
|
|
if res != nil {
|
|
|
|
return &res.Claims
|
|
|
|
}
|
|
|
|
}
|
2023-01-13 15:22:03 +00:00
|
|
|
values := url.Values{
|
|
|
|
"grant_type": []string{"client_credentials"},
|
|
|
|
"client_id": []string{a.oauthConfig.ClientID},
|
|
|
|
"username": []string{username},
|
|
|
|
"password": []string{password},
|
|
|
|
"scope": []string{strings.Join(a.oauthConfig.Scopes, " ")},
|
|
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", a.endpoint.TokenURL, strings.NewReader(values.Encode()))
|
|
|
|
if err != nil {
|
|
|
|
a.log.WithError(err).Warning("failed to create token request")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
2023-02-14 23:22:56 +00:00
|
|
|
res, err := a.publicHostHTTPClient.Do(req)
|
2023-01-13 15:22:03 +00:00
|
|
|
if err != nil || res.StatusCode > 200 {
|
2023-02-06 19:26:43 +00:00
|
|
|
b, err := io.ReadAll(res.Body)
|
|
|
|
if err != nil {
|
|
|
|
b = []byte(err.Error())
|
|
|
|
}
|
|
|
|
a.log.WithError(err).WithField("body", string(b)).Warning("failed to send token request")
|
2023-01-13 15:22:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var token TokenResponse
|
|
|
|
err = json.NewDecoder(res.Body).Decode(&token)
|
|
|
|
if err != nil {
|
|
|
|
a.log.WithError(err).Warning("failed to parse token response")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// Parse and verify ID Token payload.
|
|
|
|
idToken, err := a.tokenVerifier.Verify(context.Background(), token.IDToken)
|
|
|
|
if err != nil {
|
|
|
|
a.log.WithError(err).Warning("failed to verify token")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract custom claims
|
|
|
|
var claims *Claims
|
|
|
|
if err := idToken.Claims(&claims); err != nil {
|
|
|
|
a.log.WithError(err).Warning("failed to convert token to claims")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if claims.Proxy == nil {
|
|
|
|
claims.Proxy = &ProxyClaims{}
|
|
|
|
}
|
|
|
|
claims.RawToken = token.IDToken
|
|
|
|
return claims
|
|
|
|
}
|