Logto is an Auth0 alternative designed for modern apps and SaaS products. It offers both Cloud and Open-source services to help you quickly launch your identity and management (IAM) system. Enjoy authentication, authorization, and multi-tenant management all in one.
We recommend starting with a free development tenant on Logto Cloud. This allows you to explore all the features easily.
In this article, we will go through the steps to quickly build the SAML sign-in experience (user authentication) with Go and Logto.
Prerequisites
- A running Logto instance. Check out the introduction page to get started.
- Basic knowledge of Go.
- A usable SAML account.
Create an application in Logtoβ
Logto is based on OpenID Connect (OIDC) authentication and OAuth 2.0 authorization. It supports federated identity management across multiple applications, commonly called Single Sign-On (SSO).
To create your Traditional web application, simply follow these steps:
- Open the Logto Console. In the "Get started" section, click the "View all" link to open the application frameworks list. Alternatively, you can navigate to Logto Console > Applications, and click the "Create application" button.
- In the opening modal, click the "Traditional web" section or filter all the available "Traditional web" frameworks using the quick filter checkboxes on the left. Click the "Go" framework card to start creating your application.
- Enter the application name, e.g., "Bookstore," and click "Create application".
π Ta-da! You just created your first application in Logto. You'll see a congrats page which includes a detailed integration guide. Follow the guide to see what the experience will be in your application.
Integrate Go SDKβ
- 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.
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
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")
}
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.
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:
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:
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:
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:
func main() {
// ...
logtoConfig := &client.LogtoConfig{
Endpoint: "<your-logto-endpoint>", // E.g. http://localhost:3001
AppId: "<your-application-id>",
AppSecret: "<your-application-secret>",
}
// ...
}
You can find and copy "App Secret" from application details page in Admin Console:
Then, you can create a LogtoClient
for each user request with the Logto config above:
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))
})
// ...
}
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:
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 the callback routeβ
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.
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-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:
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:
- Run your application, you will see the sign-in button.
- Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
- After you signed in, you will be redirected back to your application and see the sign-out button.
- Click the sign-out button to clear token storage and sign out.
Add SAML connectorβ
To enable quick sign-in and improve user conversion, connect with Go as an identity provider. The Logto social connector helps you establish this connection in minutes by allowing several parameter inputs.
To add a social connector, simply follow these steps:
- Navigate to Console > Connectors > Social Connectors.
- Click "Add social connector" and select "SAML".
- Follow the README guide and complete required fields and customize settings.
If you are following the in-place Connector guide, you can skip the next section.
Set up Standard SAML appβ
Create social IdP's account and register SAML application (IdP)β
Let's go through configurations of SAML connector.
Before we kicking off, you can go to a social identity provider which supports SAML protocol and create your own account. Okta, OneLogin, Salesforce and some other platforms support authentication based on SAML protocol.
If your IdP mandate the encryption of SAML assertion and receiving of signed authentication requests, you should generate your private key and corresponding certificate using RSA algorithm. Keep the private key for your SP use and upload the certificate to IdP.
You also need to configure the ACS (Assertion Consumer Service) URL as ${your_logto_origin}/api/authn/saml/${connector_id}
to handle IdP's SAML assertion. Where you can find your connectorId
at SAML connector's details page in Logto's Admin Console.
Per current Logto's design, we only support Redirect-binding for sending authentication request and POST-binding for receiving SAML assertion. Although this sounds not cool, but we believe that the current design can handle most of your use cases. If you have any problems, feel free to reach out!
Configure SAML connector (SP)β
In this section, we will introduce each attribute in detail.
entityID Required
β
entityID
(i.e. issuer
) is Entity identifier. It is used to identify your entity (SAML SP entity), and match the equivalence in each SAML request/response.
signInEndpoint Required
β
The IdP's endpoint that you send SAML authentication requests to. Usually, you can find this value in IdP details page (i.e. IdP's SSO URL
or Login URL
).
x509Certificate Required
β
The x509 certificate generated from IdPs private key, IdP is expected to have this value available.
The content of the certificate comes with -----BEGIN CERTIFICATE-----
header and -----END CERTIFICATE-----
tail.
idpMetadataXml Required
β
The field is used to place contents from your IdP metadata XML file.
The XML parser we are using does not support customized namespace. If the IdP metadata comes with namespace, you should manually remove them. For namespace of XML file, see reference.
assertionConsumerServiceUrl Required
β
The assertion consumer service (ACS) URL is the SP's endpoint to receive IdP's SAML Assertion POST requests. As we mentioned in previous part, it is usually configured at IdP settings but some IdP get this value from SAML authentication requests, we hence also add this value as a REQUIRED field. It's value should look like ${your_logto_origin}/api/authn/saml/${connector_id}
.
signAuthnRequestβ
The boolean value that controls whether SAML authentication request should be signed, whose default value is false
.
encryptAssertionβ
encryptAssertion
is a boolean value that indicates if IdP will encrypt SAML assertion, with default value false
.
The signAuthnRequest
and encryptAssertion
attributes should align with corresponding parameters of IdP setting, otherwise error will be thrown to show that configuration does not match.
All SAML responses need to be signed.
requestSignatureAlgorithmβ
This should be aligned with the signature algorithms of IdP so that Logto can verify the signature of the SAML assertion. Its value should be either http://www.w3.org/2000/09/xmldsig#rsa-sha1
, http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
or http://www.w3.org/2001/04/xmldsig-more#rsa-sha512
and the default value is http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
.
messageSigningOrderβ
messageSigningOrder
indicates the signing and encrypting order of IdP, it's value should be either sign-then-encrypt
or encrypt-then-sign
and the default value is sign-then-encrypt
.
privateKey and privateKeyPassβ
privateKey
is an OPTIONAL value and is required when signAuthnRequest
is true
.
privateKeyPass
is the password you've set when creating privateKey
, required when necessary.
If signAuthnRequest
is true
, the corresponding certificate generated from privateKey
is required by IdP for checking the signature.
encPrivateKey and encPrivateKeyPassβ
encPrivateKey
is an OPTIONAL value and is required when encryptAssertion
is true
.
encPrivateKeyPass
is the password you've set when creating encPrivateKey
, required when necessary.
If encryptAssertion
is true
, the corresponding certificate generated from encPrivateKey
is required by IdP for encrypting SAML assertion.
For keys and certificates generation, openssl
is a wonderful tool. Here is sample command line that might be helpful:
openssl genrsa -passout pass:${privateKeyPassword} -out ${encryptPrivateKeyFilename}.pem 4096
openssl req -new -x509 -key ${encryptPrivateKeyFilename}.pem -out ${encryptionCertificateFilename}.cer -days 3650
privateKey
and encPrivateKey
files are enforced to be encoded in pkcs1
scheme as pem string, which means the private key files should start with -----BEGIN RSA PRIVATE KEY-----
and end with -----END RSA PRIVATE KEY-----
.
nameIDFormatβ
nameIDFormat
is an OPTIONAL attribute that declares the name id format that would respond. The value can be among urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
, urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
, urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName
, urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
and urn:oasis:names:tc:SAML:2.0:nameid-format:transient
, and the default value is urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified
.
timeoutβ
timeout
is the time tolerance for time validation, since the time between your SP entity and IdP entity could be different and network connection may also bring some delay. The unit is in millisecond, and the default value is 5000 (i.e. 5s).
profileMapβ
Logto also provide a profileMap
field that users can customize the mapping from the social vendors' profiles which are usually not standard. Each profileMap
keys is Logto's standard user profile field name and corresponding value should be social profiles field name. In current stage, Logto only concern 'id', 'name', 'avatar', 'email' and 'phone' from social profile, only 'id' is REQUIRED and others are optional fields.
Config typesβ
Name | Type | Required | Default Value |
---|---|---|---|
signInEndpoint | string | true | |
x509certificate | string | true | |
idpMetadataXml | string | true | |
entityID | string | true | |
assertionConsumerServiceUrl | string | true | |
messageSigningOrder | encrypt-then-sign | sign-then-encrypt | false | sign-then-encrypt |
requestSignatureAlgorithm | http://www.w3.org/2000/09/xmldsig#rsa-sha1 | http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 | http://www.w3.org/2001/04/xmldsig-more#rsa-sha512 | false | http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 |
signAuthnRequest | boolean | false | false |
encryptAssertion | boolean | false | false |
privateKey | string | false | |
privateKeyPass | string | false | |
nameIDFormat | urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified | urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress | urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName | urn:oasis:names:tc:SAML:2.0:nameid-format:persistent | urn:oasis:names:tc:SAML:2.0:nameid-format:transient | false | urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified |
timeout | number | false | 5000 |
profileMap | ProfileMap | false |
ProfileMap fields | Type | Required | Default value |
---|---|---|---|
id | string | false | id |
name | string | false | name |
avatar | string | false | avatar |
string | false | ||
phone | string | false | phone |
Referenceβ
- Profiles for the OASIS Security Assertion Markup Language (SAML) V2.0
- samlify - Highly configuarable Node.js SAML 2.0 library for Single Sign On
Save your configurationβ
Double check you have filled out necessary values in the Logto connector configuration area. Click "Save and Done" (or "Save changes") and the SAML connector should be available now.
Enable SAML connector in Sign-in Experienceβ
Once you create a social connector successfully, you can enable it as a "Continue with SAML" button in Sign-in Experience.
- Navigate to Console > Sign-in experience > Sign-up and sign-in.
- (Optional) Choose "Not applicable" for sign-up identifier if you need social login only.
- Add configured SAML connector to the "Social sign-in" section.
Testing and Validationβ
Return to your Go app. You should now be able to sign in with SAML. Enjoy!
Further readingsβ
End-user flows: Logto provides a out-of-the-box authentication flows including MFA and enterprise SSO, along with powerful APIs for flexible implementation of account settings, security verification, and multi-tenant experience.
Authorization: Authorization defines the actions a user can do or resources they can access after being authenticated. Explore how to protect your API for native and single-page applications and implement Role-based Access Control (RBAC).
Organizations: Particularly effective in multi-tenant SaaS and B2B apps, the organization feature enable tenant creation, member management, organization-level RBAC, and just-in-time-provisioning.
Customer IAM series Our serial blog posts about Customer (or Consumer) Identity and Access Management, from 101 to advanced topics and beyond.