ssomg-react
TypeScript icon, indicating that this package has built-in type declarations

2.0.5 • Public • Published

SSOMG

This is the react client for the SSOMG single sign on project, designed to work with React. Version 2.0.0 is a major redesign using hooks, context, and typescript.

Setup

Add this package with the cli command

npm install --save ssomg-react

and require it in your root App.js file with

import Ssomg from "ssomg-react";

you'll also need react-router-dom

import { Route, Link, BrowserRouter } from "react-router-dom";

add the user context provider to your index.js:

import React from 'react';
import { BrowserRouter } from "react-router-dom";
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { UserProvider } from "ssomg-react"

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <UserProvider>
        <App />
      </UserProvider>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

Note that it is inside a browser router. It will only redirect users back to their entrypoint if inside a router. If you're not using a router for some reason you can use the provided UserProviderNoRouter instead, but this is not recommended.

You can then get access to session details via the context api.

import React, { useContext } from 'react'
import { UserContext } from "ssomg-react"

export default function UserDetails() {
  const { user, logout, refresh, status, jwt, STATUS } = useContext(UserContext); 
  return (
    <header>
      Welcome, {user.first_name}.
    </header>
  )
}

Tokens and the user info are automatically refreshed in the background when close to expiry. This can be done on demand by calling the refresh method.

You can will need to add a logout route/button by yourself, just call the logout method to terminate the session.

The raw JWTs for the current app and linked services are provided. so you can use it for networking if you want to, but it's recommended to use the provided hooks for simplicity.

Networking

Ssomg provides a wrapper for Axios, and provides a nice api for making http requests.

Create a new Ssomg Network like so:

function DataExample() {
  const { data } = useEndpoint("/v2-0-0/accounts");
  // do something with the response data
}

...and you're done! this hook will do a get request to your backend and handle all authorization headers for you, and give you back the response body.

If you are waiting on some data to figure out which endpoint to call and need to call the endpoint conditionally, then you can still use the useEndpoint hook. Just pass the endpoint as undefined and it will not send the request until the endpoint is updated. Updating the endpoint will automatically request the new endpoint and update the data.

There are lower-level functions which do this too, which you can use to post data or get data in a custom way.

function DataExample() {
  const { get, post } = useApi();
  function handleSubmit(body) {
    post("/v2-0-0/accounts", body)
      .then(...)
  }
}

Requests can then be made using: the get and post methods from the useApi hook, both of which return promises. See axios docs for usage of the response object.

By default creating a new network uses environment variables to figure things out, however you can use the same network approach to get resources from other ssomg authenticated apis. First, you must add the other app as a linked service in Ssomg, and then pass the appropriate props to the hooks:

const { data } = useEndpoint("/v2-0-0/accounts", {}, "xxxxxx", "https://myapp.com");

or 

const { get, post } = useApi({}, "xxxxxx", "https://myapp.com");

You can use this to create a simple custom hook for an api like so:

// useMyApp.ts
import React from "react";
import {useEndpoint} from "ssomg-react";

// export relevant types for your app if using typescript
export interface Client {
  id: string,
  name: string,
  ...
}

export default function useMyApp(endpoint: string) {
  const { data } = useEndpoint(endpoint, {}, "xxxxxxxxxx", "https://amyapp.com");
  return data;
}

Make sure that the api endpoints are protected on the server with the appropriate roles, otherwise the requests will be return a HTTP status 403 and axios will throw an error.

Environment

REACT_APP_PUB_KEY REACT_APP_APP_ID NODE_ENV REACT_APP_NODE_HOST REACT_APP_SSO_HOST

When you register the app and the users in the main SSOMG admin, you'll be issued with an app id the public key used to verify tokens. You'll need to add the following attributes to your environment file to make sure it works correctly:

NODE_ENV=production (this ensures secure cookies are used)
REACT_APP_PUB_KEY=""-----BEGIN PUBLIC KEY-----\nMIICI...." // replace newlines with \n to limit key to one line. 
REACT_APP_APP_ID=xxxxxxxxxxxxxxxxxxxxxxxx
REACT_APP_NODE_HOST="" // leave blank to use the same host for react and the backend.
REACT_APP_SSO_HOST=https://auth.mysite.com

Using react, these can set up separately for each environment with .env.development, .env.test and .env.production files. Due to the way react compiles and is delivered as static assets, after a project is built environment variables cannot be referenced dynamically. To get around this and have multiple production versions of the app ( eg staging ) with different env variables, creating a file like the one below and include it before react in the index.html head. This can be used to override env variables. do not store any sensitive information in environment variables.

// /public/index.html 
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="%PUBLIC_URL%/env-config.js"></script>
    ...
    ...
  

// /public/env-config.js
window._env_ = {
  REACT_APP_PUB_KEY:"-----BEGIN PUBLIC KEY-----\nmypublickeyexample\n-----END PUBLIC KEY-----"
}

Gotchas

Make sure the URLs in the env file and the provider app contain the correct protocol(http(s)), and ports. Without the correct protocols, the app will behave unexpectedly.

Who do I talk to?

If there's a problem, open an issue or talk to Henry.

Readme

Keywords

Package Sidebar

Install

npm i ssomg-react

Weekly Downloads

1

Version

2.0.5

License

ISC

Unpacked Size

29.5 kB

Total Files

17

Last publish

Collaborators

  • thehenrymcintosh