github.com/brioux/go-keycloak@v0.0.0-20240929191119-b54a3a01d90b/authentication.go (about) 1 package keycloak 2 3 import ( 4 "context" 5 "fmt" 6 ) 7 8 // AuthenticationService handles communication with Keyloak authentication 9 type AuthenticationService service 10 11 // AccessGrantRequest represents a request for grant type authentication 12 type AccessGrantRequest struct { 13 GrantType string `url:"grant_type"` 14 Scope string `url:"scope,omitempty"` 15 Username string `url:"username,omitempty"` 16 Password string `url:"password,omitempty"` 17 ClientID string `url:"client_id"` 18 ClientSecret string `url:"client_secret,omitempty"` 19 } 20 21 // OIDCToken represents a credential token to access keycloak 22 type OIDCToken struct { 23 AccessToken string `json:"access_token"` 24 ExpiresIn int `json:"expires_in"` 25 RefreshExpiresIn int `json:"refresh_expires_in"` 26 RefreshToken string `json:"refresh_token"` 27 TokenType string `json:"token_type"` 28 NotBeforePolicy int `json:"not_before_policy"` 29 SessionState string `json:"session_state"` 30 Scope string `json:"scope"` 31 } 32 33 // GetOIDCToken authenticates the access grant request 34 func (c *AuthenticationService) GetOIDCToken( 35 ctx context.Context, 36 grantReq *AccessGrantRequest, 37 ) (*OIDCToken, *Response, error) { 38 // Use client configured credentials 39 if grantReq.ClientID == "" { 40 grantReq.ClientID = c.client.clientID 41 } 42 if c.client.isConfidential && grantReq.ClientSecret == "" { 43 grantReq.ClientSecret = c.client.clientSecret 44 } 45 46 path := fmt.Sprintf("%s/%s/protocol/openid-connect/token", defaultBase, c.client.realm) 47 h := headers{contentType: formEncoded} 48 49 req, err := c.client.newRequest("POST", path, grantReq, h, false) 50 if err != nil { 51 return nil, nil, err 52 } 53 54 token := new(OIDCToken) 55 resp, err := c.client.do(ctx, req, token) 56 if err != nil { 57 return nil, resp, err 58 } 59 60 return token, resp, nil 61 }