|
| 1 | +package serviceprincipal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "github.com/golang-jwt/jwt/v5" |
| 15 | +) |
| 16 | + |
| 17 | +var ( |
| 18 | + ErrSecretInvalid = errors.New("invalid client secret provided") |
| 19 | + ErrSecretExpired = errors.New("the provided secret is expired") |
| 20 | + ErrTenantNotFound = errors.New("tenant not found") |
| 21 | + ErrClientNotFoundInTenant = errors.New("application was not found in tenant") |
| 22 | +) |
| 23 | + |
| 24 | +type TokenOkResponse struct { |
| 25 | + AccessToken string `json:"access_token"` |
| 26 | +} |
| 27 | + |
| 28 | +type TokenErrResponse struct { |
| 29 | + Error string `json:"error"` |
| 30 | + Description string `json:"error_description"` |
| 31 | +} |
| 32 | + |
| 33 | +// VerifyCredentials attempts to get a token using the provided client credentials. |
| 34 | +// See: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#get-a-token |
| 35 | +func VerifyCredentials(ctx context.Context, client *http.Client, tenantId string, clientId string, clientSecret string) (bool, map[string]string, error) { |
| 36 | + data := url.Values{} |
| 37 | + data.Set("client_id", clientId) |
| 38 | + //data.Set("scope", "https://management.core.windows.net/.default") |
| 39 | + data.Set("scope", "https://graph.microsoft.com/.default") |
| 40 | + data.Set("client_secret", clientSecret) |
| 41 | + data.Set("grant_type", "client_credentials") |
| 42 | + |
| 43 | + tokenUrl := fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", tenantId) |
| 44 | + encodedData := data.Encode() |
| 45 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenUrl, strings.NewReader(encodedData)) |
| 46 | + if err != nil { |
| 47 | + return false, nil, nil |
| 48 | + } |
| 49 | + req.Header.Set("Accept", "application/json") |
| 50 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 51 | + req.Header.Set("Content-Length", strconv.Itoa(len(encodedData))) |
| 52 | + |
| 53 | + res, err := client.Do(req) |
| 54 | + if err != nil { |
| 55 | + return false, nil, err |
| 56 | + } |
| 57 | + defer func() { |
| 58 | + _, _ = io.Copy(io.Discard, res.Body) |
| 59 | + _ = res.Body.Close() |
| 60 | + }() |
| 61 | + |
| 62 | + if res.StatusCode == http.StatusOK { |
| 63 | + var okResp TokenOkResponse |
| 64 | + |
| 65 | + if err := json.NewDecoder(res.Body).Decode(&okResp); err != nil { |
| 66 | + return false, nil, err |
| 67 | + } |
| 68 | + |
| 69 | + extraData := map[string]string{ |
| 70 | + "rotation_guide": "https://howtorotate.com/docs/tutorials/azure/", |
| 71 | + "tenant": tenantId, |
| 72 | + "client": clientId, |
| 73 | + } |
| 74 | + |
| 75 | + // Add claims from the access token. |
| 76 | + if token, _ := jwt.Parse(okResp.AccessToken, nil); token != nil { |
| 77 | + claims := token.Claims.(jwt.MapClaims) |
| 78 | + |
| 79 | + if app := claims["app_displayname"]; app != nil { |
| 80 | + extraData["application"] = fmt.Sprint(app) |
| 81 | + } |
| 82 | + } |
| 83 | + return true, extraData, nil |
| 84 | + } else { |
| 85 | + var errResp TokenErrResponse |
| 86 | + if err := json.NewDecoder(res.Body).Decode(&errResp); err != nil { |
| 87 | + return false, nil, err |
| 88 | + } |
| 89 | + |
| 90 | + switch res.StatusCode { |
| 91 | + case http.StatusBadRequest, http.StatusUnauthorized: |
| 92 | + // Error codes can be looked up by removing the `AADSTS` prefix. |
| 93 | + // https://login.microsoftonline.com/error?code=9002313 |
| 94 | + d := errResp.Description |
| 95 | + switch { |
| 96 | + case strings.HasPrefix(d, "AADSTS700016:"): |
| 97 | + // https://login.microsoftonline.com/error?code=700016 |
| 98 | + return false, nil, ErrClientNotFoundInTenant |
| 99 | + case strings.HasPrefix(d, "AADSTS7000215:"): |
| 100 | + // https://login.microsoftonline.com/error?code=7000215 |
| 101 | + return false, nil, ErrSecretInvalid |
| 102 | + case strings.HasPrefix(d, "AADSTS7000222:"): |
| 103 | + // The secret has expired. |
| 104 | + // https://login.microsoftonline.com/error?code=7000222 |
| 105 | + return false, nil, ErrSecretExpired |
| 106 | + case strings.HasPrefix(d, "AADSTS90002:"): |
| 107 | + // https://login.microsoftonline.com/error?code=90002 |
| 108 | + return false, nil, ErrTenantNotFound |
| 109 | + default: |
| 110 | + return false, nil, fmt.Errorf("unexpected error '%s': %s", errResp.Error, errResp.Description) |
| 111 | + } |
| 112 | + default: |
| 113 | + return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) |
| 114 | + } |
| 115 | + } |
| 116 | +} |
0 commit comments