-
-
Save hendisantika/0fbf946f3e36e3c0aeeb4f9021dcdd80 to your computer and use it in GitHub Desktop.
login-keycloak-post.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func loginPost(in *AuthParam, reqInfo RequestInfo) (*SignInResponse, error) { | |
keycloakURL := os.Getenv("KEYCLOAK_URL") + "auth/realms/" + os.Getenv("KEYCLOAK_REALM_NAME") + "/protocol/openid-connect/token" | |
clientToken := base64.StdEncoding.EncodeToString([]byte(os.Getenv("KEYCLOAK_ADMIN_CLIENT_SECRET"))) | |
form := url.Values{ | |
"grant_type": {"password"}, | |
"username": {in.Username}, | |
"password": {in.Password}, | |
"scope": {"openid"}, | |
} | |
client := &http.Client{Timeout: 10 * time.Second} | |
req, err := http.NewRequest("POST", keycloakURL, bytes.NewBufferString(form.Encode())) | |
if err != nil { | |
return nil, status.Error(KeycloakUnreachableCode, KeycloakUnreachable) | |
} | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") | |
req.Header.Add("Authorization", "Basic "+clientToken) | |
resp, err := client.Do(req) | |
if err != nil { | |
return nil, status.Error(KeycloakUnreachableCode, KeycloakUnreachable) | |
} | |
defer resp.Body.Close() | |
if resp.StatusCode >= 400 { | |
if resp.StatusCode == http.StatusUnauthorized { | |
return nil, errors.New(AuthFailed) | |
} | |
return nil, status.Error(KeycloakUnreachableCode, KeycloakUnreachable) | |
} | |
respByte, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return nil, status.Error(KeycloakUnreachableCode, KeycloakUnreachable) | |
} | |
signIn := SignInResponse{} | |
if err := json.Unmarshal(respByte, &signIn); err != nil { | |
return nil, status.Error(KeycloakUnreachableCode, KeycloakUnreachable) | |
} | |
return &signIn, nil | |
} | |
type SignInResponse struct { | |
AccessToken string `json:"access_token"` | |
ExpiresIn int64 `json:"expires_in"` | |
RefreshExpiresIn int64 `json:"refresh_expires_in"` | |
RefreshToken string `json:"refresh_token"` | |
TokenType string `json:"token_type"` | |
IdToken string `json:"id_token"` | |
NotBeforePolicy int64 `json:"not-before-policy"` | |
SessionState string `json:"session_state"` | |
Scope string `json:"scope"` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment