github.com/brioux/go-keycloak@v0.0.0-20240929191119-b54a3a01d90b/examples/access-grants/main.go (about)

     1  // Package main provides an example for using an admin account or
     2  // a service account to authorize against a client and query a user
     3  // provided a 'query-users' role
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"log"
    10  	"net/http"
    11  	"os"
    12  
    13  	keycloak "github.com/hugocortes/go-keycloak"
    14  	"github.com/joho/godotenv"
    15  )
    16  
    17  var ctx = context.Background()
    18  
    19  // UserInfo represents preconfigured mappers for given client
    20  type UserInfo struct {
    21  	Sub string `json:"sub"`
    22  }
    23  
    24  // init loads the .env file
    25  func init() {
    26  	err := godotenv.Load()
    27  	if err != nil {
    28  		log.Fatalf("Could not load ENV file %s", err)
    29  	}
    30  }
    31  
    32  func main() {
    33  	httpClient := &http.Client{}
    34  
    35  	serviceAccount := keycloak.NewServiceAccount(
    36  		httpClient,
    37  		os.Getenv("BASE_URL"),
    38  		os.Getenv("REALM"),
    39  		true,
    40  		os.Getenv("CLIENT_ID"),
    41  		os.Getenv("CLIENT_SECRET"),
    42  	)
    43  
    44  	confidentialAdmin := keycloak.NewConfidentialAdmin(
    45  		httpClient,
    46  		os.Getenv("BASE_URL"),
    47  		os.Getenv("REALM"),
    48  		true,
    49  		os.Getenv("CLIENT_ID"),
    50  		os.Getenv("CLIENT_SECRET"),
    51  		os.Getenv("ADMIN_USER"),
    52  		os.Getenv("ADMIN_PASS"),
    53  	)
    54  
    55  	publicAdmin := keycloak.NewPublicAdmin(
    56  		httpClient,
    57  		os.Getenv("BASE_URL"),
    58  		os.Getenv("REALM"),
    59  		true,
    60  		os.Getenv("PUBLIC_CLIENT_ID"),
    61  		os.Getenv("ADMIN_USER"),
    62  		os.Getenv("ADMIN_PASS"),
    63  	)
    64  
    65  	fmt.Println("Validating service acount:")
    66  	validate(serviceAccount)
    67  	fmt.Println("Validating confidential admin:")
    68  	validate(confidentialAdmin)
    69  	fmt.Println("Validating public admin:")
    70  	validate(publicAdmin)
    71  }
    72  
    73  func validate(kc *keycloak.Client) {
    74  	token, resp, err := kc.Authentication.GetOIDCToken(
    75  		context.Background(),
    76  		&keycloak.AccessGrantRequest{
    77  			GrantType: "password",
    78  			Username:  os.Getenv("EXAMPLE_USERNAME"),
    79  			Password:  os.Getenv("EXAMPLE_PASSWORD"),
    80  		},
    81  	)
    82  
    83  	if err != nil {
    84  		fmt.Println(err.Error())
    85  		os.Exit(1)
    86  	}
    87  	fmt.Printf("user token request")
    88  	fmt.Printf("status code: %d \n", resp.Response.StatusCode)
    89  	fmt.Printf("token: %s \n", token.AccessToken)
    90  
    91  	// Get the user's token mapping by issuing a request with user token
    92  	reader, resp, err := kc.UMA.GetUMAUser(
    93  		context.Background(),
    94  		"Bearer "+token.AccessToken,
    95  		new(UserInfo),
    96  	)
    97  	if err != nil {
    98  		fmt.Println(err.Error())
    99  		os.Exit(1)
   100  	}
   101  
   102  	// GetUMAUser returns an interface that should be decoded to match our struct
   103  	userInfo, ok := reader.(*UserInfo)
   104  	if !ok {
   105  		fmt.Println("error")
   106  		os.Exit(1)
   107  	}
   108  
   109  	userID := userInfo.Sub
   110  	fmt.Printf("User ID: %s\n", userID)
   111  
   112  	// Issue request using admin token
   113  	user, resp, err := kc.AdminUser.GetUserByID(
   114  		context.Background(),
   115  		userID,
   116  	)
   117  	if err != nil {
   118  		fmt.Println(err.Error())
   119  		os.Exit(1)
   120  	}
   121  	fmt.Printf("User name: %v\n", *user.Username)
   122  }