All posts by admin

Enumerable properties in Javascript

ref – https://www.geeksforgeeks.org/what-does-enumerable-property-mean-in-javascript/

An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for…in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default.


output:

registration
name
age
marks

Since all the properties are initialized by property initializer, they all have enumerable set to true by default. To explicitly change the internal enumerable attribute of a property, the Object.defineProperty() method is used. Also, to check whether a property is enumerable or not, we use the function propertyIsEnumerable(). It returns true if the property is enumerable or false otherwise.


output:

true
true
true
false

Properties that are created using the defineProperty() method have enumerable flag set to false. When the same above code is run using a for loop, the “marks” property is not visible.


Output:

registration
name
age

Function in React called twice

ref – https://stackoverflow.com/questions/50819162/why-is-my-function-being-called-twice-in-react

When you create a project using create-react-app, it puts the App component inside React.StrictMode tags.

Document says:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:

Class component constructor method
The render method
setState updater functions (the first argument)
The static getDerivedStateFromProps lifecycle
The shouldComponentUpdate method

It is expected that setState updaters will run twice in strict mode in development.

This helps ensure the code doesn’t rely on them running a single time.

If your setState updaters are pure functions (as they should be) then this shouldn’t affect the logic of your application.

If you do not want this effect, do this:

Server side rendering (isomorphic React apps) – Data

Server

We start the server side.

At the GET verb of any url..we already have code where we store initial state in our redux. This time, let’s start it off by fetching data.

We create an initial state object, when store fetched data into an array called repositoryNames. Remember that in order to fetch in Node, we need to either use axios, or node-fetch package.

server.js

Notice thunk. Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.

Once that is done, we create our store, and place it in Provider component. Then place that into StaticRouter within our appMarkup.

This is so that we can inject it into our HTML component.

We then return this HTML component in our response object to the client.

Client Side

We do the same and apply thunk for the client. Since we already have the store and initial app state, it will match up with what the server has.

Before in App.js, where we declare our mapping to props with initialText and changeText handler, we dispatch a very simple Action object with a literal object like so:

which then get passed to reducers/index.js to be processed like so. The initialText is a simple string so we can do this:

But now, we use action objects defined in actions/index.js for more complicated procedures:

Thus, now in Home.js, we declare mapDispatchToProps with the action object getRepositoryNames:

ref – https://reactjs.org/docs/hooks-effect.html

That way, we can use getRepositoryNames inside of Home component. Since Home is a functional component, we use useEffectuseEffect runs after every render!

By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

This is the basic case in our example.

Hence we check for props repositoryNames. If its valid, we’ll display it. If it isn’t, we’ll fetch the data so it can be rendered.

Also, useEffect has a nifty feature where it can look at a state variable. If that state changes, it will run the effect. In our case, it would fetch. Hence, I put two use cases of this:

1) value changes after each click. useEffect will run every time the button is clicked because onClick updates value everytime.
2) value changes once after clicks. So useEffect will run the first time, value updates, runs second time, and that’s it.

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.