Next.Js — User Authentication with WSO2 Identity Server

  • Very SEO-friendly
  • Fast time-to-market
  • Develop applications with Server-Side-Rendering, Static-Site-Generation,
    Client-Side-Rendering and Incremental-Stastical-Regeneration easily.

1. Create a Service Provider in the WSO2 Identity Server Management Console.

  • Download the latest version of the identity server. Currently, the latest release is 5.11.0
  • Download the “ZIP Archive” and extract it. Go to <extracted_path>/bin/ directory and start the identity server.
./wso2server.sh
  • Access the management console application https://localhost:9443/carbon on the browser. you can log in to the application using super admin credentials.
username : admin
password : admin
  • Create a new service provider.
  • Enter a name for the service provider and click Register.
  • You will be redirected to the new service provider page.
  • Expand the “Inbound Authentication Configuration”. Then expand the “OAuth/OpenID Connect Configuration” and click Configure to add the OAuth/OpenID Connect protocol configuration to our service provider.
  • Add the below URL as the Callback Url and this is required for the NextAuth.js as the callback. More information about this callback URL can be found here.
http://{host}/api/auth/callback/wso2is
Eg: http://localhost:3000/api/auth/callback/wso2is
  • Click on Add button at the bottom of the page.
  • You will be redirected to the previous application page. you can find the client_id and client_secret from the “OAuth/OpenID Connect Configuration” section in Inbound Authentication Configurations.

2. Create New User

  • Click on Add button in the Users and Roles section in the left side pane.
  • Click on Add New User.
  • Add the information to the required fields and click Finish.

3. Allow CORS Requests

[cors]
allow_generic_http_requests = true
allow_any_origin = false
allowed_origins = [
"http://localhost:3000"
]
allow_subdomains = false
supported_methods = [
"GET",
"POST",
"HEAD",
"OPTIONS"
]
support_any_header = true
supported_headers = []
exposed_headers = []
supports_credentials = true
max_age = 3600
tag_requests = false
  • save the file and RESTART the WSO2IS.

4. Integrate NextAuth.js into our Next.js application

  • Install next-auth dependency. Go to the project directory and run one of the commands below.
yarn add next-auth or npm i next-auth
  • Append the following properties to .env.local file.
  • ClientID and ClientSecret can be found from the OAuth/OpenID Connect Configuration section of the application page in the management console that we created in the first step.
  • The internal_login scope is required to invoke the SCIM /Me endpoint which I will use in this application.
  • As we didn’t create new tenants, the default tenant will be the super tenant( carbon.super ).
WSO2IS_CLIENT_ID=<client_id_of_the_appliaction>
WSO2IS_CLIENT_SECRET=<client_secret_of_the_appliaction>
WSO2IS_SCOPES=openid internal_login
WSO2IS_HOST=<https://host:port>
WSO2IS_TENANT_NAME=carbon.super
  • Create a file [...nextauth].tsx in /pages/api/auth directory. This file contains all global NextAuth.js configurations. All the requests that come to /api/auth/* (sign in, signout requests) will be handled by NextAuth.js
  • Congrats, you have successfully integrated NextAuth.js with our Next.js application. And the most important thing is that we can do user authentication with the WSO2 Identity Server now :) .

5. Implement SignIn, SignOut, API invocation

  • Implement “Login with Identity Server” Button functionality
import { signIn } from "next-auth/react"<Button
onClick={(e) => {
e.preventDefault()
signIn("wso2is", { callbackUrl: "/home" })
}}
primary>
Login with Identity Server
</Button>
  • Implement Home page
  • Why use the session that is returned by getServerSideProps?
    - If you refresh the home page from a browser, and if you use usesession() hook for retrieve session, it will pop up an error. With the session returned by getServerSideProps it will always assign value for the session on every request before rendering the page.
  • why do we use the values of org and host instead of directly accessing process.env.WSO2IS_TENANT_NAME and process.env.WSO2IS_HOST from the client-side?
    - If we need to access variables on the client-side in Next.js, we need to configure them in next.config.js file. By adding the variables to next.config.js will expose the secrets to the client-side. Anyone can see these secrets. Also as the tenant name and host can vary from environment to environment, it would be better to store all the variables in one place. I chose to store them in env.* .
    The next problem is that we can’t access the variables in the env.* file from the client-side in Next.js using process.env.WSO2IS_TENANT_NAME or process.env.WSO2IS_HOST. So we need to access them from the server-side and pass them to the client-side.
  • Implement SignOut functionality.
import { signOut } from "next-auth/react"<Button
onClick={(e) => {
e.preventDefault()
signOut({ callbackUrl: "/" })
}}
primary>
Logout
</Button>
  • Invoke SCIM2 /Me Endpoint
export default function Page({ session,org }) {const { accessToken, idToken } = session}export async function getServerSideProps(context) {
return {
props: {
session: await getSession(context), org:process.env.WSO2_TENANT_NAME
}
}
}
const res = fetch(host+"/t/"+org+"/scim2/Me", {                method: 'get',
headers: new Headers({
"authorization": "Bearer " + accessToken
})
})
.then(r => r.json().then(data => ({
status: r.status, body: data })))
.then(res => {
console.log("API Response"+JSON.stringify(res))
})

6. Run the Application

  • Finally, We have one remaining task. That is to run our application :).
yarn dev or npm run dev
  • why NODE_TLS_REJECT_UNAUTHORIZED='0' is needed for running the application?
    This is because the downloadable version of the WSO2 Identity server comes with a self-signed certificate and it causes an error in the NextAuth.js authentication flow. So I have used this command as a small hack. This is not recommended for production and you should use CA-signed certificates in WSO2IS for the production environment.
  • Then open the application by accessinghttp://localhost:3000 on the browser. Let’s log in with the user that we created earlier. (Also you will be able to login with super admin credentials) . Click Continue.
  • Give the consent to access user information from our NextJS application.
  • Then you will be able to see our home page that we implemented earlier with the decoded id token information and SCIM /Me API response.
  • If you try to log out, it will be also successful and you will be redirected to the landing page of the application.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store