Hello there!

Need Help? We are right here!

Support Icon
miniOrange Email Support
success

Thanks for your Enquiry. Our team will soon reach out to you.

If you don't hear from us within 24 hours, please feel free to send a follow-up email to info@xecurify.com

Search Results:

×

OAuth Single Sign-On (SSO) for JavaScript Frameworks


miniOrange’s JavaScript OAuth Single Sign-On (SSO) solution enables secure, seamless authentication for applications built using popular JavaScript frameworks and libraries like React, Vue.js, Next.js, and Angular. By utilizing JSON Web Tokens (JWT), users can conveniently access multiple applications with just a single set of login credentials, significantly improving security and user experience.

Easily integrate OAuth 2.0 and OpenID Connect protocols into your existing JavaScript applications, effortlessly connecting them with identity providers such as Microsoft Entra ID, Okta, AWS Cognito, and others. Additionally, empower users with convenient social login options via providers like Google, Facebook, Twitter, and LinkedIn. Simplify your login processes, boost security, and deliver a smooth, frictionless experience across all your JavaScript-based apps with miniOrange SSO.

With miniOrange JavaScript OAuth SSO, you get:

  • Seamless user login experience.
  • Endless customizations to your login forms and pages.
  • Simplified customer or user on-boarding.


Connect with External Source of Users


miniOrange provides user authentication from various external sources, which can be Directories (like ADFS, Microsoft Active Directory, OpenLDAP, AWS etc), Identity Providers (like Microsoft Entra ID, Okta, AWS), and many more. You can configure your existing directory/user store or add users in miniOrange.



Prerequisites

Please make sure your organisation branding is already set under Customization >> Login and Registration Branding in the left menu of the dashboard.


Configure OAuth Application on miniOrange

  • Sign Up to the miniOrange website and login using your credentials to view the below dashboard.
  • JavaScript OAuth Single Sign-On (SSO) miniOrange Admin console

  • Navigate to the Apps section on the left side menu.
  • Click the Add Application button located at the top right corner of the page.
  •  JavaScript OAuth Single Sign-On (SSO) Add Application

  • Search for "OAuth" and select OAuth2/OpenID Connect from the miniOrange icon.
  • JavaScript OAuth Single Sign-On (SSO) Search OAuth and select OAuth2/OpenID Connect

  • Enter a name for your application in the Client Name field and provide the Redirect-URL (which will be “your_domain/sso/callback”) and Click Save. Also you can provide Logout URIs and specify where users should be redirected after Logging out.(eg. https://your_domain/login)
  • JavaScript OAuth Single Sign-On (SSO) Enter your app details

  • A toast message “App is configured successfully.” Will appear confirming the successful creation of the OAuth application on miniOrange.
  • JavaScript OAuth Single Sign-On (SSO) Getting message while configure the app

  • Locate your application name in the applications list, click the three dots menu, and select Edit.
  •  JavaScript OAuth Single Sign-On (SSO) click on three dot and select edit

  • Now copy Client Id and Client Secret and store it somewhere safe for further use.
  •  JavaScript OAuth Single Sign-On (SSO) Copy Client ID and Client Secret


Configure OAuth in JavaScript framework applications (React, Angular, Vue, Next.js, etc.)


1. Install the Connector

  • In your project’s root directory (where the package.json file is located), run the following command:
                        npm i mo-oauth-sdk
                    

2. Configure OAuth in Your Application

  • To set up OAuth, create a config.js file in your components folder and import the OAuthConfig class to configure your OAuth Configuration. The below details were provided when you created the OAuth application in miniOrange.
    Client_ID Your application client id which we copied earlier from here
    Client_Secret Your application client secret which we copied earlier from here
    BASE_URL Your base URI should look like this: https://<YOUR_DOMAIN>.xecurify.com/moas. It is your branding name followed by xecurify.com/moas.
    REDIRECT_URI This is the same redirect uri we added while configuring the OAuth app in miniOrange. It should look like this: https://<your_domain>/sso/callback
    LOGOUT_REDIRECT_URI This is the same logout uri we added while configuring OAuth app in miniOrange. It should look like this: https://<your_domain>/login
    BROKER_URI If you are using external idp other than miniOrange then go to Apps > OAuth Endpoints > Authorization Endpoint > copy 2nd Broker URL
  • Steps to Obtain Broker URL

    • Navigate to Apps section.
    •  JavaScript OAuth Single Sign-On (SSO) Navigate to Apps

    • Search for the app you created and click on menu option and select OAuth Endpoints.
    •  JavaScript OAuth Single Sign-On (SSO) Search for app and select OAuth Endpoints

    • Copy Second URI from Authorization Endpoint section under OAuth Endpoints which is your broker uri.
    •  JavaScript OAuth Single Sign-On (SSO) Copy the Authorization Endpoint


Note: Store your app credentials securely in environment variables or a properties file, and use them here.


config.js

            
              import { OAuthConfig } from 'mo-oauth-sdk';
              const conf = new OAuthConfig();
              conf.setClientId(YOUR_CLIENT_ID);
              conf.setClientSecret(YOUR_CLIENT_SECRET);
              conf.setBaseUrl(YOUR_BASE_URL);
              conf.setRedirectUri(YOUR_REDIRECT_URI);
              conf.setLogoutRedirectUri(YOUR_LOGOUT_URI); //optional
              conf.setBrokerUri(YOUR_BROKER_URI); //optional
              export default config;
            
           


3. Start the Authorization Process

  • Create a login button and use the startAuthorization method from the mo-oauth-sdk library to initiate the OAuth authorization process. you need to pass the config object to the startAuthorization function as shown below:
                        
                          import {startAuthorization} from 'mo-oauth-sdk';
                          import conf from './Conf';  //Adjust path accordingly
                          .
                          .
                          .
    
                          const login = ()=>{
                            startAuthorization(conf)
                          }
                        
                    
  • Now, when users click the login button, the OAuth flow will begin.

4. Handling Callbacks

Once the user successfully authenticates, the authorization server will redirect them to your application's /sso/callback route with authorization parameters.

To handle this:

  • Define the /sso/callback route in your application.
  • Create a Callback component and render it when the above route is accessed.
  • Invoke handleCallbackUri inside the callback component to process the authorization response.
  • Extract tokens from the response and store them securely (avoid localStorage due to security risks; prefer HTTP-only cookies or secure storage).
  • Fetch user attributes using the accessToken, create a session, and redirect the user to the dashboard.

5. Steps to Set Up the Callback Route in JS-Based Frontend Applications

You need to define the /sso/callback route in your application and create a component to handle it.


  • Install React Router if not already installed:
                                npm install react-router-dom
                            
  • Create Callback component:
                                
                                import React, { useEffect} from "react";
                                import { handleCallbackUri, TokenHandler} from 'mo-oauth-sdk';
                                import conf from './Conf'; //adjust the path accordingly
    
    
                                function Callback() {
    
    
                                    useEffect(() => {
                                        const handleCallback = async () => {
                                        const { accessToken, refreshToken, error } = await handleCallbackUri(conf, window.location.href);
    
    
                                        if (error) {
                                        // Handle errors if any
                                        return;
                                        }
                                        //Store tokens securely in your preferred storage.
                                        if (accessToken) {
                                        // Process access token and retrieve user details
                                        const { user, error } = await TokenHandler.handleAccessToken(accessToken, conf);
                                        if (user) {
                                        // Store user details securely and navigate to dashboard
                                        } else {
                                        // Handle errors if any
                                        return;
                                        }
                                        }
                                    };
                                    handleCallback();
                                    }, []);
    
    
                                    return (
                                    <div>
                                      <img src="https://i.gifer.com/ZKZx.gif" alt="Loading.." />
                                      </div>
                                    );
                                    }
    
    
                                    export default Callback;
    
                                
                            
  • Define the route in your App.js or App.tsx
                                
                                import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
                                import Callback from "./Callback"; //adjust path accordingly
                                import Home from "./Home"; 
                                    function App() {
                                    return (
                                    <Router>
                                    <Routes>
                                        {/* Existing routes..*/}
                                        <Route path="/" element={<Home />} />
                                        
                                        {/* Add new SSO callback handler here*/}
                                        <Route path="/sso/callback" element={<Callback />} />
                                        </Routes>
                                        </Router>
                                    );
                                    }
    
    
                                    export default App;
                                
                            
  • Define the route in app.routes.ts:
                                
                                import { Routes } from '@angular/router';
                                import { CallbackComponent } from './callback/callback.component';
    
    
                                export const routes: Routes = [
                                { path: 'sso/callback', component: CallbackComponent }
                                ];                    
                                
                            
  • Create callback.component.ts:
                                
                                import { Component, OnInit } from '@angular/core';
                                import { handleCallbackUri, TokenHandler } from 'mo-oauth-sdk';
                                import conf from './Conf';  //adjust the path accordingly
    
    
                                @Component({
                                …
                                })
    
    
                                export class CallbackComponent  implements OnInit {
    
    
                                async ngOnInit(): Promise {
                                const { accessToken, refreshToken, error } = await handleCallbackUri(conf, window.location.href);
    
    
                                if (error) {
                                // Handle errors if any
                                return;
                                }
    
    
                                if (accessToken) {
                                // Store and Process access token to retrieve user details
                                const { user, error } = await TokenHandler.handleAccessToken(accessToken, this.myconfig);
    
    
                                if (user) {
                                    // Store user details securely and navigate to dashboard
                                } else {
                                    // Handle errors if any
                                    return;
                                }
                                }
                                }
                            
                                
                            
  • Installing Vue Router
                                npm install vue-router@4
                            
  • Create callback.vue component:
                                
                                import { onMounted } from 'vue';
                                import { handleCallbackUri, TokenHandler } from 'mo-oauth-sdk';
                                import conf from './Conf'; //adjust the path accordingly
    
    
                                onMounted(async () => {
                                const { accessToken, refreshToken, error } = await handleCallbackUri(conf, window.location.href);
    
    
                                if (error) {
                                // Handle errors if any
                                return;
                                }
    
    
                                //Store tokens securely in your preferred storage.
                                    if (accessToken) {
                                    // Process access token and retrieve user details
                                    const { user, error } = await TokenHandler.handleAccessToken(accessToken, conf);
                                    if (user) {
                                    // Store user details securely and navigate to dashboard
                                    } else {
                                    // Handle errors if any
                                    return;
                                    }
                                    }
                                }
                                });
                                
                            
  • Create a router.js or router.ts file if not already and register callback route in it.
                                
                                    import { createRouter, createWebHistory } from 'vue-router';
                                    import Home from './components/Home.vue';
                                    import Dashboard from './components/Dashboard.vue';
    
    
                                    const routes = [
                                    {
                                    // Your existing routes
                                    },
                                    {
                                    //add callback route
                                    path: '/callback',
                                    name: 'Callback',
                                    component: Callback
                                    }
                                    ];
                                    const router = createRouter({
                                    history: createWebHistory(),
                                    routes
                                    });
    
    
                                    export default router;
                                
                            

6. Logout (Clear Session) Optional

  • To log out the user and clear the miniOrange session from the browser, call the logout function provided by the library.
  • Refer the code snippet below:
                        
                        import { logout} from "mo-oauth-sdk";
                        import conf from './Conf'; //adjust the path accordingly
                        const logoutUser= async()=>{
                            logout(conf);
                        }
                    

7. Check Session (Optional)

Check Session

  • You can check the validity of the access token using the isSessionActive method. This method verifies whether the token is still valid or has expired. You can perform this check on each page load or at regular intervals during user activity.
  • You can perform this check on each page load or at regular intervals during user activity.
                                
                                    import {isSessionActive} from "mo-oauth-sdk";
                                    
                                    const validateToken=async() => {
                                        let response = await isSessionActive(conf, accessToken)
                                        if(response)
                                            //session is active do nothing
                                            else{
                                        //logout user and redirect to session expiration page
                                        }
                                    }
                                
                            
  • If the token has expired, you can either obtain a new access token using the refresh token or log out the user and redirect them to a session-expired page, prompting them to log in again.
  • Requesting new access token:
                                
                                import {  TokenHandler} from "mo-oauth-sdk";
    
    
    
                                const getNewToken= async()=>{
                                    const refreshToken =  //fetch your stored refresh token
                                    const {error, access_token} = await TokenHandler.getNewAccessToken(refreshToken, conf);
                                    
                                        if(!error){
                                            //update new access token
                                            return;
                                        }
                                        //handle errors if any
                                        console.log("Error in getting new access token..", error)
                                    }
    
                                
                            

8. Test OAuth Authentication

Expected Flow:

  • The user clicks the Login button.
  • The startAuthorization method redirects them to the authorization server’s login page.
  • After successful authentication, the authorization server redirects the user back to the application's /sso/callback route.
  • The callback handler processes the response, retrieves tokens, and logs in the user.

This completes the OAuth login process, allowing the user to access the application securely.


Want To Schedule A Demo?

Request a Demo
  



Our Other Identity & Access Management Products