Skip to main content

Go SDK guide

This guide will show you how to integrate Logto into your Go web application.

tip
  • The following demonstration is built upon the Gin Web Framework. You may also integrate Logto into other frameworks by taking the same steps.
  • The Go sample project is available on our Go SDK repo.

Prerequisites

  • A Logto Cloud account or a self-hosted Logto (Check out the ⚡ Get started guide to create one if you don't have).
  • A Logto traditional web application created.

Installation

Execute in the project root directory:

go get github.com/logto-io/go

Add the github.com/logto-io/go/client package to your application code:

main.go
// main.go
package main

import (
"github.com/gin-gonic/gin"
// Add dependency
"github.com/logto-io/go/client"
)

func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.String(200, "Hello Logto!")
})
router.Run(":3000")
}

Integration

Create a session storage

In traditional web applications, the user authentication information will be stored in the user session.

Logto SDK provides a Storage interface, you can implement a Storage adapter based on your web framework so that the Logto SDK can store user authentication information in the session.

note

We do NOT recommend using cookie-based sessions, as user authentication information stored by Logto may exceed the cookie size limit. In this example, we use memory-based sessions. You can use Redis, MongoDB, and other technologies in production to store sessions as needed.

The Storage type in the Logto SDK is as follows:

github.com/logto-io/client/storage.go
package client

type Storage interface {
GetItem(key string) string
SetItem(key, value string)
}

We use github.com/gin-contrib/sessions middleware as an example to demonstrate this process.

Apply the middleware to the application, so that we can get the user session by the user request context in the route handler:

main.go
package main

import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
)

func main() {
router := gin.Default()

// We use memory-based session in this example
store := memstore.NewStore([]byte("your session secret"))
router.Use(sessions.Sessions("logto-session", store))

router.GET("/", func(ctx *gin.Context) {
// Get user session
session := sessions.Default(ctx)
// ...
ctx.String(200, "Hello Logto!")
})
router.Run(":3000")
}

Create a session_storage.go file, define a SessionStorage and implement the Logto SDK's Storage interfaces:

session_storage.go
package main

import (
"github.com/gin-contrib/sessions"
)

type SessionStorage struct {
session sessions.Session
}

func (storage *SessionStorage) GetItem(key string) string {
value := storage.session.Get(key)
if value == nil {
return ""
}
return value.(string)
}

func (storage *SessionStorage) SetItem(key, value string) {
storage.session.Set(key, value)
storage.session.Save()
}

Now, in the route handler, you can create a session storage for Logto:

session := sessions.Default(ctx)
sessionStorage := &SessionStorage{session: session}

Init LogtoClient

First, create a Logto config:

main.go
func main() {
// ...
logtoConfig := &client.LogtoConfig{
Endpoint: "<your-logto-endpoint>", // E.g. http://localhost:3001
AppId: "<your-application-id>",
AppSecret: "<your-application-secret>",
}
// ...
}
tip

You can find and copy "App Secret" from application details page in Admin Console:

App Secret

Then, you can create a LogtoClient for each user request with the Logto config above:

main.go
func main() {
// ...

router.GET("/", func(ctx *gin.Context) {
// Create LogtoClient
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// Use Logto to control the content of the home page
authState := "You are not logged in to this website. :("

if logtoClient.IsAuthenticated() {
authState = "You are logged in to this website! :)"
}

homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>"

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// ...
}

Config your app

Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:

  1. Your app invokes the sign-in method.
  2. The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
  3. The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in
  1. This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
  2. If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.

To learn more about the rationale and benefits of redirect-based sign-in, see Logto sign-in experience explained.


note

In the following code snippets, we assume your app is running on http://localhost:3000/.

Configure redirect URIs

Switch to the application details page of Logto Console. Add a redirect URI http://localhost:3000/callback.

Redirect URI in Logto Console

Just like signing in, users should be redirected to Logto for signing out of the shared session. Once finished, it would be great to redirect the user back to your website. For example, add http://localhost:3000/ as the post sign-out redirect URI section.

Then click "Save" to save the changes.

Handle redirect

When the user signs in successfully on the Logto sign-in page, Logto will redirect the user to the Redirect URI.

Since the redirect URI is http://localhost:3000/callback, we add the /callback route to handle the callback after signing in.

main.go
func main() {
// ...

// Add a route for handling sign-in callback requests
router.GET("/callback", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// The sign-in callback request is handled by Logto
err := logtoClient.HandleSignInCallback(ctx.Request)
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}

// Jump to the page specified by the developer.
// This example takes the user back to the home page.
ctx.Redirect(http.StatusTemporaryRedirect, "/")
})

// ...
}

Implement sign-in route

After the redirect URI is configured, we add a sign-in route to handle the sign-in request and also add an sign-in link on the home page:

main.go
func main() {
// ...

// Add a link to perform a sign-in request on the home page
router.GET("/", func(ctx *gin.Context) {
// ...
homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>" +
// Add link
`<div><a href="/sign-in">Sign In</a></div>`

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// Add a route for handling sign-in requests
router.GET("/sign-in", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// The sign-in request is handled by Logto.
// The user will be redirected to the Redirect URI on signed in.
signInUri, err := logtoClient.SignIn("http://localhost:3000/callback")
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}

// Redirect the user to the Logto sign-in page.
ctx.Redirect(http.StatusTemporaryRedirect, signInUri)
})

// ...
}

Now, when your user visit http://localhost:3000/sign-in, the user will be redirected to the Logto sign-in page.

Implement sign-out route

Similar to the sign-in flow, when the user signs out, Logto will redirect the user to the post sign-out redirect URI.

Now, let's add the sign-out route to handle the sign-out request and also add a sign-out link on the home page:

main.go
func main() {
// ...

// Add a link to perform a sign-out request on the home page
router.GET("/", func(ctx *gin.Context) {
// ...
homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>" +
`<div><a href="/sign-in">Sign In</a></div>` +
// Add link
`<div><a href="/sign-out">Sign Out</a></div>`

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// Add a route for handling signing out requests
router.GET("/sign-out", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// The sign-out request is handled by Logto.
// The user will be redirected to the Post Sign-out Redirect URI on signed out.
signOutUri, signOutErr := logtoClient.SignOut("http://localhost:3000")

if signOutErr != nil {
ctx.String(http.StatusOK, signOutErr.Error())
return
}

ctx.Redirect(http.StatusTemporaryRedirect, signOutUri)
})

// ...
}

After the user makes a signing-out request, Logto will clear all user authentication information in the session.

Checkpoint: Test your application

Now, you can test your application:

  1. Run your application, you will see the sign-in button.
  2. Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
  3. After you signed in, you will be redirected back to your application and see the sign-out button.
  4. Click the sign-out button to clear local storage and sign out.

Get user information

Display user information

To display the user's information, you can use the client.GetIdTokenClaims method. For example, add a route:

main.go
func main() {
//...

router.GET("/user-id-token-claims", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(logtoConfig, &SessionStorage{session: session})

idTokenClaims, err := logtoClient.GetIdTokenClaims()

if err != nil {
ctx.String(http.StatusOK, err.Error())
}

ctx.JSON(http.StatusOK, idTokenClaims)
})
}

Request additional claims

You may find some user information are missing in the returned object from client.GetIdTokenClaims(). This is because OAuth 2.0 and OpenID Connect (OIDC) are designed to follow the principle of least privilege (PoLP), and Logto is built on top of these standards.

By default, limited claims are returned. If you need more information, you can request additional scopes to access more claims.

info

A "claim" is an assertion made about a subject; a "scope" is a group of claims. In the current case, a claim is a piece of information about the user.

Here's a non-normative example the scope - claim relationship:

tip

The "sub" claim means "subject", which is the unique identifier of the user (i.e. user ID).

Logto SDK will always request three scopes: openid, profile, and offline_access.

To request additional scopes, you can pass the scopes to the LogtoConfig object. For example:

main.go
logtoConfig := &client.LogtoConfig{
// ...other configs
Scopes: []string{"email", "phone"},
}

Then you can access the additional claims in the return value of client.GetIdTokenClaims():

idTokenClaims, error := client.GetIdTokenClaims()
// Now you can access additional claims `claims.email`, `claims.phone`, etc.

Claims that need network requests

To prevent bloating the ID token, some claims require network requests to fetch. For example, the custom_data claim is not included in the user object even if it's requested in the scopes. To access these claims, you can use the client.FetchUserInfo() method:

userInfo, error := client.FetchUserInfo()
// Now you can access the claim `userInfo.custom_data`
This method will fetch the user information by requesting to the userinfo endpoint. To learn more about the available scopes and claims, see the Scopes and claims section.

Scopes and claims

Logto uses OIDC scopes and claims conventions to define the scopes and claims for retrieving user information from the ID token and OIDC userinfo endpoint. Both of the "scope" and the "claim" are terms from the OAuth 2.0 and OpenID Connect (OIDC) specifications.

Here's the list of supported scopes and the corresponding claims:

openid

Claim nameTypeDescriptionNeeds userinfo?
substringThe unique identifier of the userNo

profile

Claim nameTypeDescriptionNeeds userinfo?
namestringThe full name of the userNo
usernamestringThe username of the userNo
picturestringURL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.No
created_atnumberTime the End-User was created. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No
updated_atnumberTime the End-User's information was last updated. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No

Other standard claims include family_name, given_name, middle_name, nickname, preferred_username, profile, website, gender, birthdate, zoneinfo, and locale will be also included in the profile scope without the need for requesting the userinfo endpoint. A difference compared to the claims above is that these claims will only be returned when their values are not empty, while the claims above will return null if the values are empty.

note

Unlike the standard claims, the created_at and updated_at claims are using milliseconds instead of seconds.

email

Claim nameTypeDescriptionNeeds userinfo?
emailstringThe email address of the userNo
email_verifiedbooleanWhether the email address has been verifiedNo

phone

Claim nameTypeDescriptionNeeds userinfo?
phone_numberstringThe phone number of the userNo
phone_number_verifiedbooleanWhether the phone number has been verifiedNo

address

Please refer to the OpenID Connect Core 1.0 for the details of the address claim.

custom_data

Claim nameTypeDescriptionNeeds userinfo?
custom_dataobjectThe custom data of the userYes

identities

Claim nameTypeDescriptionNeeds userinfo?
identitiesobjectThe linked identities of the userYes
sso_identitiesarrayThe linked SSO identities of the userYes

urn:logto:scope:organizations

Claim nameTypeDescriptionNeeds userinfo?
organizationsstring[]The organization IDs the user belongs toNo
organization_dataobject[]The organization data the user belongs toYes

urn:logto:scope:organization_roles

Claim nameTypeDescriptionNeeds userinfo?
organization_rolesstring[]The organization roles the user belongs to with the format of <organization_id>:<role_name>No

Considering performance and the data size, if "Needs userinfo?" is "Yes", it means the claim will not show up in the ID token, but will be returned in the userinfo endpoint response.

API resources and organizations

We recommend to read 🔐 Role-Based Access Control (RBAC) first to understand the basic concepts of Logto RBAC and how to set up API resources properly.

Configure Logto client

Once you have set up the API resources, you can add them when configuring Logto in your app:

logtoConfig := &client.LogtoConfig{
// ...other configs
Resources: []string{"https://shopping.your-app.com/api", "https://store.your-app.com/api"},
}

Each API resource has its own permissions (scopes).

For example, the https://shopping.your-app.com/api resource has the shopping:read and shopping:write permissions, and the https://store.your-app.com/api resource has the store:read and store:write permissions.

To request these permissions, you can add them when configuring Logto in your app:

logtoConfig := &client.LogtoConfig{
// ...other configs
Scopes: []string{"shopping:read", "shopping:write", "store:read", "store:write"},
Resources: []string{"https://shopping.your-app.com/api", "https://store.your-app.com/api"},
}

You may notice that scopes are defined separately from API resources. This is because Resource Indicators for OAuth 2.0 specifies the final scopes for the request will be the cartesian product of all the scopes at all the target services.

Thus, in the above case, scopes can be simplified from the definition in Logto, both of the API resources can have read and write scopes without the prefix. Then, in the Logto config:

logtoConfig := &client.LogtoConfig{
// ...other configs
Scopes: []string{"read", "write"},
Resources: []string{"https://shopping.your-app.com/api", "https://store.your-app.com/api"},
}

For every API resource, it will request for both read and write scopes.

note

It is fine to request scopes that are not defined in the API resources. For example, you can request the email scope even if the API resources don't have the email scope available. Unavailable scopes will be safely ignored.

After the successful sign-in, Logto will issue proper scopes to API resources according to the user's roles.

Fetch access token for the API resource

To fetch the access token for a specific API resource, you can use the GetAccessToken method:

accessToken, error := logtoClient.GetAccessToken("https://shopping.your-app.com/api")

This method will return a JWT access token that can be used to access the API resource when the user has related permissions. If the current cached access token has expired, this method will automatically try to use a refresh token to get a new access token.

Fetch organization tokens

If organization is new to you, please read 🏢 Organizations (Multi-tenancy) to get started.

You need to add core.UserScopeOrganizations scope when configuring the Logto client:

logtoConfig := &client.LogtoConfig{
// ...other configs
Scopes: []string{core.UserScopeOrganizations},
}

Once the user is signed in, you can fetch the organization token for the user:

// Replace the parameter with a valid organization ID.
// Valid organization IDs for the user can be found in the ID token claim `organizations`.
accessToken, error := logtoClient.GetOrganizationToken("organization-id")

// or
accessTokenClaims, error := logtoClient.GetOrganizationTokenClaims("organization-id")

Organization API resources

To fetch an access token for an API resource in an organization, you can use the getAccessToken method with both the API resource and organization ID as parameters:

accessToken, error := client.GetAccessToken(
'https://shopping.your-app.com/api',
organizationId
);

Further readings