Category Archives: Uncategorized

Using Keycloak in React

ref – https://scalac.io/user-authentication-keycloak-1/

Start up your keycloak server and sign into https://localhost:8080/auth/admin

Server configuration

What you’re seeing on the page above is the default (master) realm. A realm is a domain in which several types of entities can be defined, the most prominent being:

Users: basic entities that are allowed access to a Keycloak-secured system.
Roles: a User’s authorization level, such as admin/manager/reader.
Clients: browser apps and web services that are allowed to request a login.
Identity Providers: external providers to integrate with, such as Google, Facebook, or any OpenID Connect/SAML 2.0 based system.

The master realm serves as the root for all of the others. Admins in this realm have permission to view and manage any other realm created on the server instance. Keycloak authors don’t recommend using the master realm to manage your users and applications (it is intended as space for super-admins to create other realms).

So let’s start by creating a new realm for our app named MyDemo.

Make sure that the MyDemo realm is selected. On the left sidebar, go to the Users tab and hit Add users button.

For now, the only thing you’ll need to provide is the username. Let’s call him John.
After creating the user, you’ll need to set up his password.
Go to Credentials tab, enter the new password twice and hit Reset Password.

To check if the new user works, open a new incognito window in your browser. Then go to https://localhost:8080/auth/realms/MyDemo/account and try logging in with the username john and the password you provided earlier.

Since we left the Temporary option turned on when resetting the password, you’ll be asked to provide a new one on the first login. Afterwards, you’ll be taken to your account management panel.

Among other things, this will allow you to provide your profile information (which may or may not be enforced by the admin), change your password, and see all your active login sessions. For now, let’s update the Email, First name and Last name fields with whatever values you like, then get back to the admin window.

Create Client

The final step of the initial server configuration is to create a client. Clients are browser apps and web services that are either allowed to initiate the login process or have been provided with tokens resulting from earlier logins.

Today we’ll be securing a React-based front-end, so let’s go to the Clients tab and hit the Create button:

For the Access Type, select public. Since we have no real way of hiding the secret in a JS-based browser app, this is what we need to stick with.

Next comes Valid Redirect URIs – this is the URI pattern (one or more) which the browser can redirect to after completing the login process.

Since we picked public access type for our client (and thus anyone can ask to initiate the login process), this is especially important. In a real app, you will need to make sure you make this pattern as restrictive as possible, otherwise, you could open your system to phishing attacks! However, for dev purposes, you can just leave it at default.

The last of the important options is Web Origins, which governs CORS requests. Again, for dev purposes the default value is fine.

One last thing we’ll need is the client configuration to use with our app. Go to the Installation tab and select Keycloak OIDC JSON as the format:

Download this JSON and keep it. We’ll be needing it later.

React App

open up a terminal and make sure create-react-app package is installed.

Now we use it to create a react app called keycloak-react.

create-react-app keycloak-react

Firstly, we’ll need to add some dependencies. Open package.json and add the following two items:

Now in your terminal, install all the packages

npm install

Open up the directory with VS Code.

Let’s replace the contents of src/App.js with our skeleton:

As you can see, this is just a Router providing navigation between two other components. Let’s add the first of those, src/Welcome.js:

Nothing particularly fancy here, just some generic text. The next one should be a bit more interesting – put it at src/Secured.js:

Explanation

In the secured component, as soon as the component is mounted into the DOM, we can create the Keycloak object by providing client configuration:

Remember the JSON you downloaded from the admin panel? Put it into public/keycloak.json to get the above to work. Alternatively, you could pass a matching JavaScript object to Keycloak directly like so:

login-required is one of two possible values to be passed as an onLoad parameter. This will authenticate the client if the user has already logged into Keycloak, or redirect the browser to the login page if he hasn’t. The other option is check-sso: this will only authenticate the client if the user has already logged in, otherwise the client will remain unauthenticated without automatic redirection.

Time to check it out – run npm start and your browser should open automatically. You’ll see that you have a public, and secured component.
Click on the secured one and you’ll be redirected to the login page. Log in as John and you’ll be able to see the text from the secured component.

You’ll find you can now navigate between the two components without having to log in again.

Profile Data and Logout

Let’s expand our app a little bit by adding the logout functionality and some user data extraction. We’ll start with the latter – add the following as src/UserInfo.js:

This component accepts a Keycloak instance from its parent, then uses the loadUserInfo method to extract the user’s data.

Now for the logout button, place the following in src/Logout.js:

Similarly, this accepts a Keycloak instance from the parent, then uses its logout method. Note that it has to be called last – otherwise it would redirect you to the login form again.

Let’s include these new components in src/Secured.js:

As expected, clicking the logout button forces you to have to log in again, the next time you try to access the Secured component.

Basic KeyCloak + Node JS tutorial

ref –

  • Install KeyCloak Server – https://huongdanjava.com/install-keycloak-standalone-server.html
  • Install and run Node JS with KeyCloak Server -https://medium.com/devops-dudes/securing-node-js-express-rest-apis-with-keycloak-a4946083be51
  • demo

Install Keycloak

Download Keycloak zip and unzip it onto a directory.

Go into the directory and cd into the bin folder. Then: ./standalone.sh

Open up a browser and go to http://localhost:8080/auth/

We then need to create a new user admin by filling in the Administration Console and then clicking Create button.
I will create a new user using admin/admin.

Go to the admin console http://localhost:8080/auth/admin/ and log in.

Create Realm

A Realm manages a set of users, clients, credentials, roles, and groups. A user belongs to and logs into a realm. Realms are isolated from one another and can only manage and authenticate the users that they control.

Clients are browser apps and web services that are either allowed to initiate the login process or have been provided with tokens resulting from earlier logins.

First, make sure you are logged into the Admin Console.

From the Master drop-down menu, click Add Realm. When you are logged in to the master realm this drop-down menu lists all existing realms.

Type Demo-Realm in the Name field and click Create.

Make sure Demo-Realm is selected for the below configurations. Avoid using the master realm.

Create Client for your Realm

Click on the Clients menu from the left pane. All the available clients for the selected Realm will get listed here.

To create a new client, click Create. You will be prompted for a Client ID, a Client Protocol and a Root URL. A good choice for the client ID is the name of your application nodejs-microservice, the client protocol should be set to openid-connect and the root URL should be set to the application URL of http://localhost:8000

After saving you will be presented with the client configuration page where you can assign a name and description to the client if desired.

Set the Access Type to confidential, Authorization Enabled to ON , Service Account Enabled to ON and click Save.

Credentials tab will show the Client Secret which is required for the Node.js Application Keycloak configurations later on.

Creating Client Roles

First, click on Clients > nodejs-microservice > Roles tab.

We need to create roles for this.
Do this for user and admin.

After creating those roles, you should be able to see them appear under the Roles tab of Client nodejs-microservice.

Creating Realm Roles

We have applications assign access and permissions to specific roles. Let’s create realm roles to give application access to our user and admin roles.

For example, for user boss, we want it with admin roles to be able to access, so we will create an app-admin realm role to give to this user.

for user rtsao, we want it with user roles to be able to access, so we will create an app-user realm role for this.

On the left sidebar menu, click on the roles. Click Add Role.

After Save, enabled Composite Roles and Search for nodejs-microservice under Client Roles field. Select user role of the nodejs-microservice and Click Add Selected >.

This configuration will assign nodejs-microservice user client role to the app-user realm role. We can also mix and match for more complicated permissions.

Let’s do the same for realm role app-admin.

Creating Users with realm roles

Users are entities that are able to log into your system. We can grant them our realm roles for testing purposes.

Let’s create users:

rtsao – user role only
boss – admin role only
ver – both user and admin role

On the left hand sidebar, click on Users.

On the right side of the empty user list, click Add User to open the add user page.
Enter a name in the Username field; this is the only required field. Flip the Email Verified switch from Off to On and click Save to save the data and open the management page for the new user.

Click the Credentials tab to set a temporary password for the new user.

Flip the Temporary switch from On to Off
– Type a new password and confirm it, click Reset Password to set the user password to the new one you specified.

For simplicity let’s set the password to mypassword for all the users.

Click the Role Mappings tab to assign realm roles to the user.

Realm roles list will be available in Available Roles list. Select one required role and click on the Add Selected > to assign it to the user.

After role assignment, assigned roles will be available under Assigned Roles list. Role assignments for rtsao should be app-user.

for boss, give it app-admin.

For ver, give it both app-admin and app-user.

Generating Tokens for users to access resource

Go to Realm Settings of the Demo-Realm from the left menu and click on OpenID Endpoint Configuration to view OpenID Endpoint details.

copy the token endpoint.

Open up Postman, and put it into the url.
Make sure you put http verb as POST.

Click on Body tab. Click on x-www-form-urlencoded radio button.

They put these key/values

grant_type, password
client_id, nodejs-microservice
client_secret,
username, rtsao
password, *************

This is the basics of getting an access token. With this token, you give it to keycloak’s API later in the tutorial, and it will grant you access to the URL resource.

When you hit send, you should get a status 200 and the token itself.

Copy the token and give it to https://jwt.io/ to verify.

On the right hand side, look at the payload. You should see various information. At the very bottom, you should see ‘signature verified’.

access_token includes the permission details.
realm_access.roles includes app_user realm role.
resource_access.nodejs-microservice.roles include the user client role.
preferred_username includes the username of the user (rtsao)

iat, exp includes the token issued time as well as the token expiry time. Access Token expiry times can be customizable under Realm Settings, Tokens tab. By default, Access Token Lifespan would be set to 5 minutes which can be customized based on your security requirements.

Node JS App

Make sure you have the latest node and npm.


mkdir keycloak-nodejs-microservice
cd keycloak-nodejs-microservice

npm init

It will ask you for the following information. Just keep pressing enter, and enter your name at the “author name” field.

npm install –save express
npm install -g nodemon

Open the project with VS Code.

Create a new file called index.js and with the below content.

Save the file, go to your terminal and type the following.


nodemon index.js

This will start the server. To test this app, open your browser and go to http://localhost:3000 and Server is up! message will appear in the browser.

Create sub directory Test

We want all of our resource strings to have a sub route of ‘test’. test/route1, test/route2…etc.

Create a new folder controller and create a new file test-controller.js in the created folder with the below content.

Import test-controller.js and add the testController router to express in index.js before the app.listen function call.

invoke by opening Postman and do a GET on http://localhost:3000/test/{anonymous} (user, admin, all-user)
You should get the response text accordingly because so far, no authorization is applied.

Integrating Keycloak with our Node app

Install keycloak-connect, express-session dependencies to your project.


npm install keycloak-connect –save
npm install express-session –save
npm install express-session –save

Create a new folder config and create a new file keycloak-config.js in the created folder with the below content. Change the keycloakConfig variable content with Keycloak Server URL and nodejs-microservice Client Id.

config/keycloak-config.js

Apply the Role-Based Access for our API

keycloak.protext() can be used to secure APIs in the routers.

Test it all out

Open Postman, and generate another access token like we did before. When generating, let’s use user rtsao. Remember that this user only has user role access.

Open up a tab on Postman and put GET as the http verb.
put http://localhost:3000/test/anonymous

Click on Authorization tab, type Bearer Token, then paste the token.

Click on Send. Because the anonymous url is not protected, we always get the response.

We then test on the admin, we get access denied because the token shows that we’re a user role.

When we test for role user, it all works.

Using Postman to make changes to signed-in user’s profile

prerequisites:

Azure AD B2C has an app.
This app should have these minimum permissions which you need to set:

Set up Postman to query for MS Graph API

ref – https://docs.microsoft.com/en-us/graph/use-postman

Open up Postman app.

Choose File | Import ….

Select Import From Link.

Paste the following two URLs and choose Import after each:

https://raw.githubusercontent.com/microsoftgraph/microsoftgraph-postman-collections/master/Microsoft%20Graph.postman_collection.json
https://raw.githubusercontent.com/microsoftgraph/microsoftgraph-postman-collections/master/Microsoft%20Graph.postman_environment.json

You should now see the Microsoft Graph environment in the top right environment drop down by the eye icon. Now you need to set up your environment.

Set up application API calls

Choose the No environment drop down in top right corner.

Select Microsoft Graph environment.

Choose the eye icon to the right and then choose Edit.

Enter your Microsoft Identity Application in the current (not initial) variables:
ClientID,
ClientSecret
TenantID.

When you created your app, it will have its own clientID and tenantID. For ClientSecret, just generate one like so:

Make sure you copy the secret onto a text, because after refresh, Azure will cover it.

Select Update.

Close the Manage Environments dialog box. In the MicrosoftGraph | Application collection on left side, choose
Get App-only Access Token.

Then choose Send.

You’ll get a App Access Token.

On the left sidebar, under Application, click on Get users. In your environment variables, make sure you copy and paste this App Access Token into the AppAccessToken variable.

Confirm that it is set under Bearer Token in Authorization tab.

Now you are ready to make changes to the user profile data.

On the left side, under Application | Users folder and choose Get Users.

The URL should be https://graph.microsoft.com/v1.0/users/ the HTTP method should be GET.

Then choose Send.

You’ll get a list of the users. Choose one user, and copy the id.

Changing the profile data

Now, on the top, change the HTTP method to PATCH. copy and paste the id at the end like so:

https://graph.microsoft.com/v1.0/users/302cd19a-6bd6-4cb0-a161-00cf925d8da7

Then choose Body tab. Select the raw radio button. Finally, choose JSON (application/json) for the pull down, which was originally defaulted to text.

Let’s say we want to change property displayName. We use JSON for this:

click send.

Complete binary tree vs full binary tree

ref – https://www.programiz.com/dsa/complete-binary-tree

A complete binary tree is when all nodes are filled, and the leaves are filled from the left.

A full tree is where each node has 0 or 2 children.

A complete binary tree has an interesting property that we can use to find the children and parents of any node.

If the index of any element in the array is i, the element in the index 2i+1 will become the left child and element in 2i+2 index will become the right child. Also, the parent of any element at index i is given by the lower bound of (i-1)/2.

Mosh Ultimate DS and Algo video – hash table answers