簡體   English   中英

aws amplify withAuth0 HOC:未配置 auth0 客戶端錯誤

[英]aws amplify withAuth0 HOC: the auth0 client is not configured error

遵循此處 與 auth0 聯合的文檔以添加適用於現有項目的額外登錄按鈕時遇到一些麻煩。

我已經添加了配置 object 並在 auth0 平台上創建了應用程序並配置了 cognito 以將其用作聯合登錄,但是使用AWS Amplify withAuth0 HOC讓按鈕工作似乎沒有按預期工作。 無論是那個還是文檔都不清楚。

單擊按鈕時出現以下錯誤: the auth0 client is not configured

index.js

import "@babel/polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import AppWithAuth from './appWithAuth';
import * as serviceWorker from './serviceWorker';

import { Provider } from 'react-redux';
import { createStore } from 'redux'
import rootReducer from './reducers'

const store = createStore(rootReducer);

ReactDOM.render(
  <Provider store={store}>
    <AppWithAuth />
  </Provider>,
  document.getElementById('root')
);


serviceWorker.unregister();

App.js

import React, { Component } from 'react';
import CssBaseline from '@material-ui/core/CssBaseline';
import { MuiThemeProvider, createMuiTheme, withStyles } from '@material-ui/core/styles';
import { BrowserRouter as Router } from "react-router-dom";
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import MomentUtils from '@date-io/moment';

import 'typeface-roboto';

import { connect } from 'react-redux';
import { setUserMetaLoaded, setPremiumUser, setAdminUser } from './actions';
import API from './api/appsync';

import Header from './components/header';
import MyRouter from './router';

import { library } from '@fortawesome/fontawesome-svg-core';
import { faLink } from '@fortawesome/free-solid-svg-icons';

import Amplify from 'aws-amplify';

library.add(faLink)
/*global AWS_CONFIG */
/*eslint no-undef: "error"*/
Amplify.configure(AWS_CONFIG);

const theme = createMuiTheme({
  typography: { useNextVariants: true },
  palette: {
    primary: {
      light: '#FDCF2A',
      main: '#fe9e18',
      dark: '#CC690B',
      contrastText: '#ffffff',
    }
  },
});

const styles = theme => ({
  root: {
    display: 'flex',
    flex: 1,
    justifyContent: 'center',
    padding: 20,
    maxWidth: 1000,
    margin: '0 auto',
    flexDirection: 'column'
  },
  headerRoot: {
    position: 'sticky',
    top: 0,
    paddingBottom: 3,
    zIndex: theme.zIndex.appBar,
    backgroundColor: theme.palette.background.default
  }
})

class App extends Component {
  async componentDidMount() {
    const isAdmin = await API...
    this.props.dispatch(setAdminUser(isAdmin));

    const userMeta = await API...;
    if(!userMeta) {
      this.props.dispatch(setUserMetaLoaded(true));
      this.props.dispatch(setPremiumUser(false));
      return;
    }
    if(userMeta.hasOwnProperty('SubEnd')) {
      const now = Math.floor(Date.now() / 1000);
      if(userMeta['SubEnd'] > now) {
        this.props.dispatch(setPremiumUser(true));
      } else {
        this.props.dispatch(setPremiumUser(false));
      }
    }
    this.props.dispatch(setUserMetaLoaded(true));
  }

  render() {
    const {classes} = this.props;
    if (this.props.authState !== "signedIn") {
      return null;
    }

    return (
      <MuiThemeProvider theme={theme}>
      <MuiPickersUtilsProvider utils={MomentUtils}>
        <Router>
          <CssBaseline />
          <div className={classes.headerRoot}>
            <Header />
          </div>
          <div className={classes.root}>
            <MyRouter/>
          </div>
        </Router>
      </MuiPickersUtilsProvider>
      </MuiThemeProvider>
    );
  }
}

export default connect()(
  withStyles(styles)(App)
);

appWithAuth.js

import React from "react";
import { SignIn, SignUp, forgotPassword, Greetings } from "aws-amplify-react";
import { default as CustomSignIn } from "./components/login";
import App from "./App";
import { Authenticator } from "aws-amplify-react/dist/Auth";

/*global AWS_CONFIG */
/*eslint no-undef: "error"*/
const config = AWS_CONFIG;

class AppWithAuth extends React.Component {
  render() {
    return (
      <div>
        <Authenticator hide={[SignIn, SignUp, forgotPassword, Greetings]} amplifyConfig={config}>
          <CustomSignIn />
            <App />
        </Authenticator>
      </div>
    );
  }
}

export default AppWithAuth;

從放大組件/login/index.js覆蓋默認登錄頁面的組件

import React from "react";
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { orange } from '@material-ui/core/colors';
import { SignIn } from "aws-amplify-react";
import ButtonAuth0 from "./../buttons/auth0"

const styles = theme => ({
  '@global': {
    body: {
      backgroundColor: theme.palette.common.white,
    },
  },
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center'
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1)
  },
  cognito: {
    margin: theme.spacing(3, 0, 2),
    color: theme.palette.getContrastText(orange[600]),
    backgroundColor: orange[600],
    '&:hover': {
      backgroundColor: orange[700]
    }
  }
});

class CustomSignIn extends SignIn {
  constructor(props) {
    super(props);
    this._validAuthStates = ["signIn", "signedOut", "signedUp"];
  }

  showComponent(theme) {
    const {classes} = this.props;
    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div className={classes.paper}>
          <ButtonAuth0 />
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form className={classes.form} noValidate>
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="username"
              label="Username"
              name="username"
              autoFocus
              onChange={this.handleInputChange}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              onChange={this.handleInputChange}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              color="inherit"
              className={classes.cognito}
              onClick={(event) => super.signIn(event)}
            >
              Sign In With Cognito
            </Button>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2" onClick={() => super.changeState("forgotPassword")}>
                  Reset password?
                </Link>
              </Grid>
              <Grid item>
                <Link href="#" variant="body2" onClick={() => super.changeState("signUp")}>
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
      </Container>
    );
  }
}

export default (withStyles(styles)(CustomSignIn));

按鈕組件: components/buttons/auht0.js

import React from 'react';
import { withAuth0 } from 'aws-amplify-react';
import Button from '@material-ui/core/Button';
import { red } from '@material-ui/core/colors';
import { withStyles } from '@material-ui/core';
import { Auth } from 'aws-amplify';

const auth0 = {
  "domain": "<...>",
  "clientID": "<...>",
  "redirectUri": "http://localhost:3000",
  "audience": "",
  "responseType": "token id_token", // for now we only support implicit grant flow
  "scope": "openid profile email", // the scope used by your app
  "returnTo": "http://localhost:3000"
};

Auth.configure({
  auth0
});

const styles = theme => ({
  auth0: {
    margin: theme.spacing(3, 0, 2),
    color: theme.palette.getContrastText(red[700]),
    backgroundColor: red[700],
    '&:hover': {
      backgroundColor: red[800]
    }
  }
});

const Auth0Button = (props) => (
  <div>
    <Button
      fullWidth
      variant="contained"
      color="inherit"
      className={props.classes.auth0}
      onClick={props.auth0SignIn}
    >
      Sign In With auth0
    </Button>
  </div>
)

export default withAuth0(withStyles(styles)(Auth0Button));


這應該單獨工作還是仍然需要遵循上面鏈接中文檔的步驟 1 到 4?

在這里回答我自己的問題。 奇怪的是,我不知何故沒有嘗試過這個。

查看源代碼,我嘗試將 auth0 配置 object 傳遞給 withAuth0 初始化,並消除了該錯誤消息。

export default withAuth0(withStyles(styles)(Auth0Button), auth0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM