Introduction to the

Onelogin is an excellent SSO(Single sign-on) service provider. We can easily build SSO programs with the help of Onelogin’s services.

As we discussed earlier, there are two common protocols for building SSO, OpenID Connect and SAML. Today we will use a concrete example to show how to use the Authentication Flow in OpenID Connect for SSO Authentication in Onelogin.

Introduction to OpenId Connect and Authentication Flow

OpenID Connect is built on top of OAuth 2.0 protocol. It allows clients to authenticate users based on authorization server or identity provider (IdP) and obtain basic information of users.

OpenID Connect provides a RESTful HTTP API and uses Json as the data delivery format.

We can easily use Onelogin as an Identity Provider (IdP) for SSO authentication.

Today we are going to talk about how to use Onelogin to implement Authentication Flow. We know that OpenId Connect has many modes.

Today we introduce the Authorization Code pattern.

The steps of the Authorization Code process are as follows:

The client prepares the authentication request, which contains the required parameters

The client sends the request to the authorization server

The authorization server authenticates the most popular users

Authorization service to unify/authorize end users

The authorization server sends the end user back to the client with the authorization code

The client requests a response from the Token endpoint using an authorization code

The client receives the response, and the Body of the response contains the and ID Token and the Access Token

The client validates the ID Token and gets some identity information from the user

Onelogin configuration work

If we want to use Onelogin in our application, we need to do some configuration work. So let’s see.

First we need to register an account in Onelogin.

Signing up for Onelogin is free and can be configured with 3 apps and 25 users. Testing is enough.

I won’t go into the registration process. Once registered, we can create the app in Onelogin.

In applications TAB, we want to use OpenID Connect, so search for OIDC:

As you can see, Onelogin supports multiple OIDC connection protocols. Since it is the interface of Onelogin, of course choose the connection of Onelogin.

Enter the name of the application and click Save.

In the column of the configuration, redirect URL: http://localhost:3000/oauth/callback

This is the URL to jump back to our app after the authentication.

Go to the SSO bar, copy the Client ID and Client Security, and change the authentication mode to POST

If you also want to create new users or set permissions for them, you can explore the advanced features of Onelogin on your own.

Connect to Onelogin using the application

Here we choose the official server example provided by Onelogin: github.com/onelogin/on…

Let’s download the program and rename.env.sample to.env

Modify the variables, mainly OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, SUBDOMAIN and OIDC_REDIRECT_URI, which are set during onelogin configuration:

SUBDOMAIN=flydean-dev
OIDC_CLIENT_ID=a3446600-f263-0138-3235-122333243433
OIDC_CLIENT_SECRET=**********
OIDC_REDIRECT_URI=http://localhost:3000/oauth/callback
Copy the code

Then run NPM intall; NPM start Starts the nodeJS service.

The official example uses the NodeJS + Express framework and the Passport-OpenIdConnect module to interact with Onelogin.

Let’s look at the flow of interaction.

  1. Open http://localhost:3000 with a browser and enter the main page of the APP:

  1. Click login to jump to the authorization login page of Onelogin:

Let’s look at the network request:

As you can see, the first few status codes are 302, redirected.

Redirects from the localhost:3000 login page to:

https://flydean-dev.onelogin.com/oidc/2/auth?response_type=code&client_id=a3446600-f263-0138-3235-064d76eee9d3178911&redirect_ uri=http://localhost:3000/oauth/callback&scope=openid profile&state=ohC1Fi0n0YTDELBtNmePDGvb
Copy the code

As you can see, this redirection adds parameters that need to be added in the OIDC protocol, such as respnse_type=code to use the Authorization Code mode. And client_id is the configured client ID. Redirect_uri is also the return link of the configuration.

Scope indicates the authentication scope, and state is a unique flag used to prevent brushing.

Then redirects to:

https://flydean-dev.onelogin.com/trust/openid-connect/v2?client_id=a3446600-f263-0138-3235-064d76eee9d3178911&grant=cbec20f1-f 1d8-4733-9a6f-e98471edfc13
Copy the code

In this step, Onelogin verifies the parameters passed in the previous step and then jumps again.

Then redirects to:

https://flydean-dev.onelogin.com/login
Copy the code

This is the login page for the custom domain name.

https://flydean-dev.onelogin.com/login2/?return=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmkiOiJodHRwczovL2ZseWRlYW4tZGV2Lm9uZ WxvZ2luLmNvbS90cnVzdC9vcGVuaWQtY29ubmVjdC92Mj9jbGllbnRfaWQ9YTM0NDY2MDAtZjI2My0wMTM4LTMyMzUtMDY0ZDc2ZWVlOWQzMTc4OTExXHUwM DI2Z3JhbnQ9Y2JlYzIwZjEtZjFkOC00NzMzLTlhNmYtZTk4NDcxZWRmYzEzIiwibm90aWZpY2F0aW9uIjp7Im1lc3NhZ2UiOiJDb25uZWN0aW5nIHRvICoqT 3BlbklkIENvbm5lY3QgKE9JREMpKioiLCJpY29uIjoiY29ubmVjdGlvbiIsInR5cGUiOiJpbmZvIn0sImlzcyI6Ik1PTk9SQUlMIiwiYXVkIjoiQUNDRVNTI iwiZXhwIjoxNjAyOTIwNjM0LCJwYXJhbXMiOnt9LCJtZXRob2QiOiJnZXQifQ.hoUjh18mehtBSCINkoGOSDwJFHDBBl_nn47RMSizPfw
Copy the code

Onelogin then encrypts the parameters and returns the page you can see.

  1. Enter our username and password

Click to continue.

  1. After the authentication is successful, the user information page is displayed

We can see that the interior also goes through a series of forward calls:

We need to care about the following callback:

http://localhost:3000/oauth/callback? code=2PVdwgQkNip883hql_ub9w3Byug&state=ohC1Fi0n0YTDELBtNmePDGvb
Copy the code

As you can see in the callback, we get the code that we can use later to interact with onelogin.

  1. Click on Profile and we will try to get the user’s information from Onelogin

Let’s look at the link to the request:

http://localhost:3000/users/profile
Copy the code

This step will actually request user information for Onelogin in the background via code.

Key steps in a program

The official authentication program is built with NodeJS and Express, and the authentication framework is mainly used with Passport and Paspert-OpenidConnect.

Let’s take a look at the key code.

Passport configuration uses Onelogin:

// Configure the OpenId Connect Strategy
// with credentials obtained from OneLogin
passport.use(new OneLoginStrategy({
  issuer: baseUri,
  clientID: process.env.OIDC_CLIENT_ID,
  clientSecret: process.env.OIDC_CLIENT_SECRET,
  authorizationURL: `${baseUri}/auth`.userInfoURL: `${baseUri}/me`.tokenURL: `${baseUri}/token`.callbackURL: process.env.OIDC_REDIRECT_URI,
  passReqToCallback: true
},
function(req, issuer, userId, profile, accessToken, refreshToken, params, cb) {

  console.log('issuer:', issuer);
  console.log('userId:', userId);
  console.log('accessToken:', accessToken);
  console.log('refreshToken:', refreshToken);
  console.log('params:', params);

  req.session.accessToken = accessToken;

  return cb(null, profile);
}));
Copy the code

As you can see from the code above, once you get the accessToken, it’s stored in session.

Use session to store authentication information:

app.use(session({
  secret: 'secret squirrel'.resave: false.saveUninitialized: true
}))
Copy the code

Logical operation of login:

app.get('/login', passport.authenticate('openidconnect', {
  successReturnToOrRedirect: "/".scope: 'profile'
}));
Copy the code

Logical operations for callback:

app.get('/oauth/callback', passport.authenticate('openidconnect', {
  callback: true.successReturnToOrRedirect: '/users'.failureRedirect: '/'
}))
Copy the code

To obtain a user profile:

router.get('/profile'.function(req, res, next) {
  request.get(
    `https://${ process.env.SUBDOMAIN }.onelogin.com/oidc/2/me`,   
    {
    'auth': {
      'bearer': req.session.accessToken
    }
  },function(err, respose, body){

    console.log('User Info')
    console.log(body);

    res.render('profile', {
      title: 'Profile'.user: JSON.parse(body)
    });

  });
});
Copy the code

Access user information using accessToken in session.

conclusion

A simple SSO program is set up. The accessToken information is retrieved through the Passport module and stored in the session.

Passport module supports a variety of Strategy, including the openID, Local, BrowserID, Facebook, Google, Twitter, etc. We can use it to accommodate different authentication services.

Author: Flydean program stuff

Link to this article: www.flydean.com/openid-conn…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!