Giter Site home page Giter Site logo

samples-js-react's Introduction

React Sample Applications for Okta

This repository contains several sample applications that demonstrate various Okta use-cases in your React application.

Each sample makes use of the Okta React Library.

If you haven't done so already, register for a free account at developer.okta.com. Select Create Free Account and fill in the forms to complete the registration process. Once you are done and logged in, you will see your Okta Developer Console.

Tip: You can also create an account using the Okta CLI and okta register. To create an app, run okta apps create and use the settings below.

Register your application by selecting Applications > Add Application. On the next screen, choose Single Page App and click Next.

On the following screen, edit the application settings. For React applications running in developer mode, the port number should be 8080. Configure your app as follows:

  • Base URI: http://localhost:8080
  • Login redirect URI: http://localhost:8080/login/callback
  • Logout redirect URI: http://localhost:8080

Once you have completed the form, you will be given a client ID. You will also need the issuer value for your Okta org.

The issuer is the URL of the authorization server that will perform authentication. All Developer Accounts have a "default" authorization server. The issuer is a combination of your Org URL (found in the upper right of the console home page) and /oauth2/default. For example, https://dev-133337.okta.com/oauth2/default.

These values must exist as environment variables. They can be exported in the shell, or saved in a file named testenv, located in the same directory as this README. See dotenv for more details on this file format.

ISSUER=https://yourOktaDomain.com/oauth2/default
CLIENT_ID=123xxxxx123

Please find the sample that fits your use-case from the table below.

Sample Description
Okta-Hosted Login A React application that will redirect the user to the Okta-Hosted login page of your Org for authentication. The user is redirected back to the React application after authenticating.
Custom Login Page A React application that uses the Okta Sign-In Widget within the React application to authenticate the user.

Note: npm@7 users are advised to specify --legacy-peer-deps flag during samples installation.

Quick Start: Automatic Setup with Heroku

You need a Heroku account to follow these instructions.

You can create a free Okta Developer org and deploy this app directly to Heroku by clicking the purple button:

Deploy

To deploy the app, you will need an Okta org setup as described in the section above.

You will also need to replace the config values for ISSUER and CLIENT_ID in Heroku configuration based on your Okta org. Also be sure to add your Heroku app's base URL to the list of trusted origins in your Okta admin settings.

After you deploy the app, you will also need to go to your Okta account to enable cors and configure the login and logout redirect URI in your client application settings for the newly deployed app domain if they are not preconfigured.

Note: Due to sample apps are served under different routes, base urls will be needed for the redirect uris, e.g.https://<myapp.heroku.com>/okta-hosted-login or https://<myapp.heroku.com>/custom-login.

Finally, click on View on the result screen to navigate to the newly deployed app.

You can use your Okta user credentials to login to the applications. That's it! You've successfully logged in using Okta.

Running the resource server

The samples include a page which accesses a protected resource (messages). To start the sample resource server:

npm run resource-server

Running the tests

In addition to the other environment vars, you will need credentials for a test user. Add the values for your Okta org and user in a testenv file.

ISSUER=https://yourOktaDomain.com/oauth2/default
CLIENT_ID=123xxxxx123
USERNAME[email protected]
PASSWORD=testpass

NOTE: The test suite expects you to use 8080 for your port number. Make sure your Okta app has the redirect URI if you want to test these samples.

With these variables set, you should be able to run npm test and bask in the glory of passing tests.

samples-js-react's People

Contributors

aarongranick-okta avatar codepadma avatar denysoblohin-okta avatar haishengwu-okta avatar jaredperreault-okta avatar jmelberg-okta avatar johnwargo avatar magizh-okta avatar oktauploader-okta avatar oleksandrpravosudko-okta avatar releng-internal-okta avatar robertjd avatar shiqiyang-okta avatar shuowu avatar shuowu-okta avatar swiftone avatar vijetmahabaleshwar-okta avatar wayneearl-okta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

samples-js-react's Issues

logout - missing

I'm following your sample on hot to integrate Okta into the React app from here https://developer.okta.com/quickstart/#/react/nodejs/express

it has the logout functionality that is missing from this github sample. Why?

looks to me like is not functional, after I call this.props.auth.logout('/'); nothing happens, but if I refresh the page then I'm logged out.

Can you complete this github sample to support the logout functionality?

Thx

invalid_token - "The Token has expired" instead of redirect to Login.

Hi! I'm using the okta-react SDK in my project, which is working well apart from the following issue: upon access token expiry, the client does not redirect the user to the login page as expected and a blank view is rendered with the following error:

Uncaught (in promise)
  OAuthError
    errorCode: invalid_token
    errorSummary: "The Token has expired"

Upon refreshing the page, the client is redirected to the Login page, and the site functions normally. This has made things pretty difficult to debug, since the issue goes away upon any change to the project, and I also haven't yet figured out how to change the access token age. Looking for:

  1. A resolution to access token expiry that redirects the client to the login page
  2. A way of setting the max age of the access token.

It should be noted that simply destroying the token in local storage doesn't resolve the issue.

Problem - Verify link from Sign Up returns back Error

  • Enable Okta Self-Sign up
  • User gets an email with a verify link
  • Link redirects to /implicit/callback
  • Page renders an error: "AuthSdkError: OAuth flow response state doesn't match request state"
  • Clicking on the Login button does the redirect correctly and correctly logs the user in

Why does this happen?

default file for dotenv config

These values must exist as environment variables. They can be exported in the shell, or saved in a file named testenv, at the root of this repository.

but I need to name it .env in root of okta-hosted-login root.

➜  okta-hosted-login git:(master) ✗ node --version
v12.13.0
➜  okta-hosted-login git:(master) ✗ npm --version
6.12.0

TypeError: okta_auth_js_1.default is not a constructor

React, redux with Visual studio enterprise, created default react app using Visual studio and followed step by step user guide for react application. While rendering Login Page I encountered this error:

LoginForm.tsx:18 Uncaught TypeError: okta_auth_js_1.default is not a constructor
at new LoginForm (LoginForm.tsx:18)
at constructClassInstance (react-dom.development.js:14185)
at updateClassComponent (react-dom.development.js:18394)
at beginWork$1 (react-dom.development.js:20161)
at HTMLUnknownElement.callCallback (react-dom.development.js:336)
at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
at invokeGuardedCallback (react-dom.development.js:440)
at beginWork$$1 (react-dom.development.js:25738)
at performUnitOfWork (react-dom.development.js:24662)
at workLoopSync (react-dom.development.js:24638)
at performSyncWorkOnRoot (react-dom.development.js:24237)
at react-dom.development.js:12180
at unstable_runWithPriority (scheduler.development.js:818)
at runWithPriority$2 (react-dom.development.js:12130)
at flushSyncCallbackQueueImpl (react-dom.development.js:12175)
at flushSyncCallbackQueue (react-dom.development.js:12163)
at discreteUpdates$1 (react-dom.development.js:24390)
at discreteUpdates (react-dom.development.js:1442)
at dispatchDiscreteEvent (react-dom.development.js:5885)

Login issue from another machine?

Using credentials saved in the OKTA portal, this sample-js-react, I was able to login successfully locally on my machine which I pushed into github repo and launched locally

cd custom-login
$ npm start

In browser localhost:8080 username and password, clicked LOGIN and works

but if my project was cloned on another machine, and upon launching using the same

$ npm install at the root level as well as at the custom-login folder and then
cd custom-login
$npm start

it reports
jquery.js:10245 OPTIONS https://%7Byouroktadomain%7D.com/api/v1/authn
net::ERR_NAME_NOT_RESOLVED

React -- log in with Google

Referencing this issue:
##40

I have been going back and forth with Okta support on why logging in with google isn't working and base on the issue I referenced above, is it true this isn't implemented with React yet? Okta support has been unable thus far to give me any answers yet.

So I cloned the custom-login demo and am able to authenticate with username and password to Okta. I also set up the social provider so that when I click by custom button to login with google, it seems to work. Google authenticates me and returns me to my /implicit/callback route.

Then I get the error:
AuthSdkError: Unable to parse a token from the url

But looking at the Okta logs, it looks like I was authenticated. The token is correct but the /implicit/callback route doesn't parse the URL and save in local storage.

What's the deal?

Thanks!

Custom login sample fails authentication with current instructions

Followed README, testing on my employer's dev Okta tenant. Using a custom domain name as the issuer, so it is different from the *-admin.oktapreview.com developer portal url.

Tested on Firefox. Steps taken:

  1. Run npm install in both custom-login and okta-hosted-login
  2. Create new SPA application as per documentation (no option given to provide a base URL, so the documentation is out of date)
  3. Assign "Everyone" to application on developer portal
  4. Create testenv file with issuer and client ID found on developer portal
  5. Run npm start in custom-login project
  6. Attempt sign in and observe POST request to {oktaBaseUrl}/api/v1/authn that returns HTTP 401
  7. Shut down custom-login and run npm start in okta-hosted-login
  8. Attempt sign in to and observe GET request to {oktaBaseUrl}/oauth2/default/api/v1/authorize that returns HTTP 200
  9. With a successful sign in, shut down okta-hosted-login and restart custom-login
  10. Observe login form bypassed, due to valid cookie, and a successful authentication

Improve debuggability for okta-react

currently when i have an auth error i get this:

image

and because everything is abstracted away inside Security.js and ImplicitCallback.js, i dont get to debug the error. thrown errors are caught. i suggest either log out more information about the errors, or just dont catch the thrown errors so we can debug things ourselves.

Registration failed with Sign-in widget

Registration failing with custom attribute. Otherwise it results in success with base attributes.

{errorCode: "E0000001", errorSummary: "Api validation failed: null", errorLink: "E0000001",…}
errorCauses: [{errorSummary: "Registration cannot be completed at this time", reason: "UNKNOWN",…}]
0: {errorSummary: "Registration cannot be completed at this time", reason: "UNKNOWN",…}
domain: "registration request"
errorSummary: "Registration cannot be completed at this time"
reason: "UNKNOWN"
errorCode: "E0000001"
errorId: "oaeXsTbBwLdRTa423R_1JcklQ"
errorLink: "E0000001"
errorSummary: "Api validation failed: null"

Add a sample test to prove tests work when Okta is integrated

With Okta React 3.0.4, I get a test failure after creating an app and adding the SDK.

TypeError: Cannot read property 'emit' of undefined
  18 | test('renders learn react link', async () => {
  19 |   await act(async () => {
> 20 |     ReactDOM.render(<App/>, container);
     |              ^
  21 |   });
  22 | 
  23 |   const linkElement = container.querySelector('a');
  at AuthService.emit (node_modules/@okta/okta-react/dist/AuthService.js:579:30)
  at AuthService.emitAuthState (node_modules/@okta/okta-react/dist/AuthService.js:182:12)
  at AuthService.clearAuthState (node_modules/@okta/okta-react/dist/AuthService.js:175:12)
  at new AuthService (node_modules/@okta/okta-react/dist/AuthService.js:78:10)
  at node_modules/@okta/okta-react/dist/Security.js:29:33

I don’t get this error with 3.0.1. Proof in https://github.com/mraible/schematics/pull/1.

I tried to modify my test to mock tiny-emitter, but it still doesn’t work.

test('renders learn react link', async () => {
  jest.mock("tiny-emitter", () => {
    return {
      on: jest.fn(),
      off: jest.fn(),
      emit: jest.fn()
    }
  });
  
  await act(async () => {
    ReactDOM.render(<App/>, container);
  });
  
  const linkElement = container.querySelector('a');
  expect(linkElement.textContent).toBe('Learn React');
});

More descriptive error message

It's a bit frustration when I saw such page without any hints (no error from console and network as well)
wonder if we'd like to display error details which would be helpful for troubleshooting!
(given it's sample project, I doubt there would be security concern but please suggest)

screen shot 2018-05-02 at 12 01 59 pm

Works fine in developer account, but not in organisation account

I followed the instructions here:
https://github.com/okta/samples-js-react/tree/master/okta-hosted-login

And here:
https://github.com/okta/samples-java-spring/tree/master/resource-server

...to set up a sample reactjs app authenticating with Okta.

Worked like a charm with my developer Okta account.

But when I tried to use my organisation's Okta configurations, I'm encounter errors while trying to bring up the resource server.

Here are the configurations in my application.yml:

okta:
  oauth2:
    issuer: "https://<myOrgName>.okta-emea.com/oauth2/default"
    client-id: "<myClientId>"
    client-secret: "<myClientSecret>"

I created a new application in Okta developer console with a Web configuration, which gave me the clientId and clientSecret.

And when I do this:

cd resource-server
mvn

I see this error:

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.8.RELEASE:run (default-cli) on project okta-spring-boot-oauth-resource-server: An exception occurred while running. null: InvocationTargetException: Failed to process import candidates for configuration class [org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerConfiguration]; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerTokenServicesConfiguration$JwkTokenStoreConfiguration: 401 Unauthorized -> [Help 1]

Any pointers on what I'm missing? How can I troubleshoot what is going wrong? Any logs in Okta?

How should an SPA choose a client ID?

I've seen this question posed a couple of times, but haven't found the answer.

What is the best practice for an SPA that must choose from multiple client IDs when authenticating a user? I'm guessing that the answer is the same regardless of whether those client IDs equate to multiples instances of the same app configured under one org, or multiples instances of the same app appearing in multiple orgs via the OIN.

Should specific URLs map to a client ID? This would require users to log in using a specific URL:
myapp.mycompany.com/friendly_name_for_client_id_1
myapp.mycompany.com/friendly_name_for_client_id_2

Should subdomains map to a client ID? This would require users to log in using a specific subdomain:
friendly_name_for_client_id_1.myapp.mycompany.com/
friendly_name_for_client_id_2.myapp.mycompany.com/

I hope there is a simpler answer. Any help is appreciated.

Okta hosted sign in page not loading in IE (Using React App and implicit flow)

Hi Team,

We have implemented okta security for React-App ( Single page app) by using implicit flow. Which redirects user to Organization Okta hosted login page. This is working perfectly in Chrome, however it's not working in IE.

When I try to access react app(localhost:3000/) in chrome it shows Okta hosted sign in page and once I login then it lands me to base URL. However in IE it's not asking me for sign in instead it's loading header and footer of app and not loading the secured content/component.

Can you please suggest something in this.

Cannot login to custom-login example?

I have modified the custom-login/src/.sample.config.js

clientId
issuer: 'https://dev-193534.com/oauth2/default'

once npm starts in custom-login folder

Compiled successfully!

You can now view samples-js-react in the browser.

Local: http://localhost:8080/
On Your Network: http://192.168.1.7:8080/

Then browser localhost:8080 login and forgotten password, made request and changed password, but after using the email as username and newly created password, it is still

Unable to connect to the server. Please check your network connection.

On the admin page, I have already created SPA app.

Then next time doing the same rerquest for new password I cannot even get another one

this time also

Unable to connect to the server. Please check your network connection.

Issue with NoMatch component

Hi,

Right now I'm working on adding a NoMatch component for my application and when I added the Route:

const NotFound = () => <h1>Not Found</h1>;
class App extends Component {
  render() {
    return (
      <Router>
        <Security
          issuer={config.oidc.issuer}
          client_id={config.oidc.clientId}
          redirect_uri={config.oidc.redirectUri}
        >
          <Navbar />
          <Container text style={{ marginTop: '7em' }}>
            <Route path="/" exact component={Home} />
            <Route path="/implicit/callback" component={ImplicitCallback} />
            <SecureRoute path="/messages" component={Messages} />
            <SecureRoute path="/profile" component={Profile} />
            <Route component={NotFound}/>
          </Container>
        </Security>
      </Router>
    );
  }
}

The NotFound always get rendered on every route.

The code is exactly the same as in okta-hosted-login plus the NotFound mentioned above.

okta-hosted-login - Failed to Load Config...

I hit an issue running the okta-hosted-login.

Starting the development server...

/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

Error: Failed to load config "airbnb" to extend from.
Referenced from: /Users/pc/Dev/octa/samples-js-react/.eslintrc.json
    at configMissingError (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:289:9)
    at ConfigArrayFactory._loadExtendedShareableConfig (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:877:23)
    at ConfigArrayFactory._loadExtends (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:780:25)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:719:25)
    at _normalizeObjectConfigDataBody.next (<anonymous>)
    at ConfigArrayFactory._normalizeObjectConfigData (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:664:20)
    at _normalizeObjectConfigData.next (<anonymous>)
    at ConfigArrayFactory.loadInDirectory (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/config-array-factory.js:510:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js:378:46)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/Users/pc/Dev/octa/samples-js-react/okta-hosted-login/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js:397:20) {
  messageTemplate: 'extend-config-missing',
  messageData: {
    configName: 'airbnb',
    importerName: '/Users/pc/Dev/octa/samples-js-react/.eslintrc.json'
  }

The base eslint config needs to be in the same folder as package.json, node_modules, and where you run the eslint command.

found the suggestion here : airbnb/javascript#2202

Copying .eslintrc.json from samples-js-react to samples-js-react/okta-hosted-login got everything working for me.
NB I did have some issues loading up the eslint libraries so it's possible this is related to that rather than the project code you have here.

Blocked by CORS policy

I just cloned the samples-js-react repo, npm installed the dependencies and tried to start up a development server. When I load the page I see the menu at the top but no contents on the rest of the screen. If I click the "Login" link at the top, I'm redirected to a blank page. Opening the Chrome console shows the following exception getting triggered:

Access to XMLHttpRequest at 'https://<mysubdomain>.okta.com/oauth2/default/.well-known/openid-configuration' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I'm not very experienced with React so I'm unsure if this is something in my local configuration causing this behavior or if the package is broken somehow. I'm using dotenv file to pass the issuer and client ID. Any help would be greatly appreciated!

AuthSdkError

Hi when npm start and accessed using machine name instead of localhost, AuthSdkError shows up as the app is not using HTTPS.

How to resolve this issue?

Thanks !

Error showing during NPM of Okta-Hosted-Login

Just FYI. there is an error showing during the npm install of the Okta-Hosted-Login

Terminal output

git clone [email protected]:okta/samples-js-react.git
Cloning into 'samples-js-react'...
remote: Counting objects: 474, done.
remote: Compressing objects: 100% (42/42), done.
remote: Total 474 (delta 25), reused 20 (delta 12), pack-reused 420
Receiving objects: 100% (474/474), 2.20 MiB | 1.54 MiB/s, done.
Resolving deltas: 100% (214/214), done.
➜  Code cd samples-js-react/okta-hosted-login
➜  okta-hosted-login git:(master) npm install

> [email protected] install /Users/bretterer/Code/samples-js-react/okta-hosted-login/node_modules/fsevents
> node install

node-pre-gyp ERR! Tried to download(404): https://fsevents-binaries.s3-us-west-2.amazonaws.com/v1.1.2/fse-v1.1.2-node-v59-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for [email protected] and [email protected] (node-v59 ABI) (falling back to source compile with node-gyp)
  SOLINK_MODULE(target) Release/.node
  CXX(target) Release/obj.target/fse/fsevents.o
  SOLINK_MODULE(target) Release/fse.node
  COPY /Users/bretterer/Code/samples-js-react/okta-hosted-login/node_modules/fsevents/lib/binding/Release/node-v59-darwin-x64/fse.node
  TOUCH Release/obj.target/action_after_build.stamp

> [email protected] postinstall /Users/bretterer/Code/samples-js-react/okta-hosted-login/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js


> [email protected] postinstall /Users/bretterer/Code/samples-js-react/okta-hosted-login
> node post-install.js

Creating default configuration file..

Sample project is ready to go!  Please add your configuration to src/.samples.config.js, see the README for instructions.

added 1293 packages in 36.88s

NPM version: 5.6.0
Node Version: v9.5.0

custom login sample app keeps loading even after successful login.

I'm trying out the custom login app, after failing to implement it on my own,
replacing the config file with my own config file and running the app,

  • on failed login it shows a failed to login message which is correct.
  • on successful login it just keeps on loading...

React Component inside Dynamics 365.

Hi Okta Dev Team,

We are building a react component which needs to call an external API. The react component is hosted in Dynamics 365.

The Dynamics 365 has 2 factor authentication with Okta.

How to enable the OIDC in this react component similar to :
https://pcf.gallery/react-aad-msal-pcf/
https://taerimhan.com/using-react-aad-msal-to-call-a-secure-api-from-a-pcf-control/

The challenge we are facing is in the redirect uri and the callback setup.

Any suggestions would be highly appreciated.

Thank you

Okta react authentication sample cors error

Hi, I've followed your guide I've enabled CORS on my org account, here's a preview:
image
However I'm getting an error when registrering an account: Access to XMLHttpRequest at 'https://xx-dev-753152.okta.com/api/v1/authn' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
any ideas?

Error: Cannot read property 'getAuthState' of undefined

Hi All, I am getting below error while running my app:

Error: Cannot read property 'getAuthState' of undefined
TypeError: Cannot read property 'getAuthState' of undefined
    at node_modules/@okta/src/Security.tsx:48:24
    at useReducer (node_modules/react-dom/cjs/react-dom-server.node.development.js:1194:57)
    at Object.useState (node_modules/react-dom/cjs/react-dom-server.node.development.js:1132:10)
    at Object.useState (node_modules/react/cjs/react.development.js:1497:21)
    at Security (node_modules/@okta/okta-react/bundles/okta-react.cjs.js:53:31)
    at processChild (node_modules/react-dom/cjs/react-dom-server.node.development.js:3043:14)
    at resolve (node_modules/react-dom/cjs/react-dom-server.node.development.js:2960:5)
    at ReactDOMServerRenderer.render (node_modules/react-dom/cjs/react-dom-server.node.development.js:3435:22)
    at ReactDOMServerRenderer.read (node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
    at renderToString (node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)

below is the code:

import React from 'react';
import {StaticRouter, Route} from 'react-router-dom';
import { OktaAuth } from '@okta/okta-auth-js';
import {Security, SecureRoute, LoginCallback} from '@okta/okta-react';
import firstpage from './FirstPage';

const oktaAuth = new OktaAuth({
  issuer: 'https://abcdef.okta.com'',
  clientId: 'abcdabcd',
  redirectUri: window.location.origin + '/callback'
});

function Root() {
    return (
            <StaticRouter>
                <Security oktaAuth={oktaAuth}>
                    <SecureRoute
                        path="/abc/xyz"
                        component={firstpage}
                    />
                    <Route
                        path="/implicit/callback"
                        component={LoginCallback}
                    />
                </Security>
            </StaticRouter>
    );
}
export default hot(module)(Root);
"@okta/okta-auth-js": "^4.7.1",
"@okta/okta-react": "^4.1.0",

node -v = v12.21.0
npm -v = 6.14.11

can you suggest what could be the issue here?

Error in user guide on this JS SDK

There is an error in the usage guide on this SDK here:

https://developer.okta.com/docs/guides/sign-into-spa/react/configure-the-sdk/

You need to pass an array to scope in the config like so:

const config = {
  clientId: '{clientId}',
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  redirectUri: 'http://localhost:8080/implicit/callback',
  scope: ['openid', 'profile', 'email'],
};

With 'openid profile email', I don't get an automatic redirection to Okta when authentication is required. When manually triggering via auth.login(), I receive:

Unhandled Rejection (TypeError): oauthParams.scopes.join is not a function

multiple client ids when okta-react integration is published on OIN.

We are building a Single Page App (SPA) with React and are using the okta-react library to implement OIDC auth flow.

When our Okta integration gets published on OIN, every customer will have a different client id. But we are not sure how to add different per-customer client IDs to the react code. What’s the best way to obtain client id to initialize the okta-react library? The callback URL does include issuer in headers but not client id (Also seems like SPAs that use OIDC, only need client_id and client_secret isn’t needed.)

If anyone has experience with this, we really appreciate any advice.

okta logout fails

I pulled the sample applications project, tried out the okta-hosted-login. I was able to login successfully, but when I clicked on the logout button it doesn't log me out.

Unhandled Rejection (AuthApiError): Not found: Resource not found: me (Session).

It seems to be failing on the /api/v1/session/me call to destroy the session, the session is not found.

I was not getting this logout issue before.

Custom-login sample does not login/auth due to CORS error

I set up the custom sample as per the provided documentation.

I then set my .samples.config.js with the following based on my sample app

export default {
  oidc: {
    clientId: '0oafpegi83aS2ATgd0h7',
    issuer: 'https://dev-458373.oktapreview.com/oauth2/default',
    redirectUri: 'http://localhost:8080/implicit/callback',
    scope: 'openid profile email',
  },
  resourceServer: {
    messagesUrl: 'http://localhost:8000/api/messages',
  },
};

Running the sample fails at the login when I enter correct credentials with a message in the GUI

We found some errors. Please review the form and make corrections.

Looking at the Chrome console I can see the request to the auth URL has failed with a CORS issue. The console error message is:

Failed to load https://dev-458373.oktapreview.com/api/v1/authn: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Scope is not getting passed properly to okta-react

I tried adding

<Security
         issuer={config.oidc.issuer}
         client_id={config.oidc.clientId}
         redirect_uri={config.oidc.redirectUri}
         scopes={config.oidc.scope}
> 

in App.jsx but even that is not getting reflected properly in the token.

Introspect API

We're using this demo with the introspect api on the /oauth2/v1/introspect using the generated pkce token. Is this possible? Would it be possible to get an example using the rest api?

Authorization header Message.jsx line 32

This line I had to change it to Authorization: Bearer ${accessToken.value} or accessToken.accessToken for this to work with the example node js resource server you provided. Otherwise, it just sends the whole access token object back to the node server and it doesn't know how to process

Okta-hosted-login redirect loop after okta-react bump

I started seeing this issue after bumping okta react dependency to 3.0.9.

To Replicate - update okta-react dependency to 3.0.9, start okta-hosted-login app.
After logging in, it should show this error in the demo app.

Screen Shot 2020-11-12 at 6 46 07 PM

It works when I click on the Login button on this page again.
It also do many redirects when I click on logout after that.
Screen Shot 2020-11-12 at 6 48 29 PM

I was seeing this issue in my project, so, i replicated this on the demo project and bumped the okta-react dependency.
I forked the samples-js-react project to demonstrate the issue - https://github.com/phyolim/samples-js-react/tree/okta-react-bump

List Group Members throwing an error

{
"errorCode": "E0000007",
"errorSummary": "Not found: Resource not found: {{GROUPID}} (UserGroup)",
"errorLink": "E0000007",
"errorId": "oaeIp2gJC9iR_mSLH6kapkAHw",
"errorCauses": []
}

NOTES
Groupid removed as did not want this public

Social login

I've tried to add Facebook/Google auth with these samples but I haven't been able to do it.

This is my Security component.


const config = {
  issuer: "url",
  redirect_uri: window.location.origin + "/implicit/callback",
  client_id: "client",
  idps: [
    { type: "FACEBOOK", id: "id" },
    { type: "GOOGLE", id: "id" }
  ],
  idpDisplay: "PRIMARY"
};

function Root() {
  return (
    <Switch>
      <Security
        issuer={config.issuer}
        client_id={config.client_id}
        redirect_uri={config.redirect_uri}
        idps={config.idps}
        idpDisplay={config.idpDisplay}
      >
        <Route exact path="/" component={Home} />
        <Route path="/implicit/callback" component={ImplicitCallback} />
        <Route path="/login" component={Login} />
      </Security>
    </Switch>
  );
}

Is there any way to configure social login with React okta library?

OktaSignIn widget hangs silently if not provided a client id

Found this troubleshooting what turned out to be a typo. If the client id doesn't get passed to the widget, it hangs without any errors.

To reproduce, simply comment out this line:

I'm assuming spinning silently forever is not the expected behavior. I would expect an error to be thrown or some sort of message to show up. Not sure if this is an issue with the example or with the widget itself.

Redirecting from login

I have recreated this example for a React application on the okta docs.

Example Repo:
https://github.com/mbychkowski/okta-example

When I am logged out and access the protected link I get directed to the login form and then redirected to the protected page. This works as I expect it to.

However,
when I am logged out and try to access the login link I get directed again to the login form, but fail to redirect me to the protected page root page. Instead I receive this in the URL "http://localhost:3000/implicit/[object%20Object]". I have verified that I am logged in, however just not redirected after authentication.

Any ideas why this might be happening? Is there a solution?

Custom login form

Is it possible to use a completely custom login form?

I see you still using the login widget

import * as OktaSignIn from '@okta/okta-signin-widget';

Out-of-date versions of @okta/okta-react and @okta/okta-signin-widget

Hello
I am quite new to okta. I have tried to plug okta to an existing react app. I had an hard time figuring out why things where not working in my app while my code was quite similar to the custom login sample...
Using the versions of okta-react and okta-signin-widget used in the samples solved all my problems.
Latest versions of these two libs may have breaking changes.
Sadly I have not seen any migration tips from okta-react 2 to okta-react 3 in the doc :(

React custom-login

I am getting the following error displayed on the okta widget when I attempt to login:

Unable to connect to the server. Please check your network connection.

The console provides an additional error which I pasted below.

I am unable to log in by using developer credentials. I am confident I set up the application and config file properly. I did not touch any other file.

OPTIONS https://dev-######.okta.com.com/api/v1/authn net::ERR_CERT_COMMON_NAME_INVALID
  | send | @ | jquery.js:10245
-- | -- | -- | --
  | ajax | @ | jquery.js:9734
  | jqueryRequest | @ | jqueryRequest.js:17
  | httpRequest | @ | http.js:43
  | post | @ | http.js:118
  | postToTransaction | @ | tx.js:53
  | postToTransaction | @ | clientBuilder.js:173
  | ./node_modules/@okta/okta-signin-widget/node_modules/@okta/okta-auth-js/lib/clientBuilder.js.proto.signIn | @ | clientBuilder.js:176
  | doPrimaryAuth | @ | okta-sign-in.entry.js:40650
  | (anonymous) | @ | okta-sign-in.entry.js:40594
  | startTransaction | @ | okta-sign-in.entry.js:34007
  | save | @ | okta-sign-in.entry.js:40593
  | _fulfilled | @ | q.js:834
  | (anonymous) | @ | q.js:863
  | Promise.promise.promiseDispatch | @ | q.js:796
  | (anonymous) | @ | q.js:604
  | runSingle | @ | q.js:137
  | flush | @ | q.js:125
  | run | @ | setImmediate.js:40
  | runIfPresent | @ | setImmediate.js:69
  | onGlobalMessage | @ | setImmediate.js:109
  | postMessage (async) |   |  
  | registerImmediate | @ | setImmediate.js:120
  | setImmediate | @ | setImmediate.js:27
  | nextTick | @ | q.js:180
  | Promise.then | @ | q.js:856
  | (anonymous) | @ | okta-sign-in.entry.js:38702
  | triggerEvents | @ | backbone.js:352
  | triggerApi | @ | backbone.js:339
  | eventsApi | @ | backbone.js:137
  | Events.trigger | @ | backbone.js:329
  | __save | @ | okta-sign-in.entry.js:23553
  | (anonymous) | @ | underscore.js:804
  | submit | @ | okta-sign-in.entry.js:23037
  | dispatch | @ | jquery.js:5226
  | elemData.handle | @ | jquery.js:4878
-- | --

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.