B2B Saas Authentication

/

Frontend SDKs

/

Headless

/

RBAC

/

Is Authorized

isAuthorized

The SDK provides two methods for getting an authorization verdict on a Resource-action pair (that is, whether the logged-in Member is authorized to perform the specified action on the specified Resource).

The isAuthorizedSync method will use locally-cached instances of the Member and the configured RBAC policy. If the RBAC policy has not been loaded, this method will always return false. The SWR caching strategy is detailed here.

The isAuthorized method determines whether the logged-in member is allowed to perform the specified action on the specified resource. It will return a Promise that resolves after the RBAC policy has been loaded. Returns true if the member can perform the action, false otherwise.

If the member is not logged in, this method will always return false. If the resource or action provided are not valid for the configured RBAC policy, this method will return false.

As a best practice, authorization checks for sensitive actions should also occur on the backend.

In React, the @stytch/react library provides the useStytchIsAuthorized hook that implements these methods for you. It returns two boolean values.

  • isAuthorized indicates whether the Member is authorized. It could be false even if the Member is actually authorized if the result is from the cache and the underlying data has changed.
  • fromCache indicates whether the value was returned from the application cache. If true, a state refresh is in progress.

In Next.js, useStytchIsAuthorized also returns a third boolean value.

  • isInitialized indicates whether the cache is initialized.

import { useStytchIsAuthorized } from '@stytch/react/b2b';

export const EditDocuments = () => {
  const { isAuthorized } = useStytchIsAuthorized('documents', 'edit');

  const editDocument = () => {
    //...
  };

  return (
    <button disabled={!isAuthorized} onClick={editDocument}>
      Edit
    </button>
  );
};

RESPONSE

200
{
    "status_code": 200,
    "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141"
    "is_authorized": true,
}