Возникли проблемы с выполнением документов здесь с федерацией auth0 для добавления дополнительной кнопки входа в систему, которая работает в существующем проекте.
Я добавил объект конфигурации и создал приложение наПлатформа 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;
Компонент, который переопределяет страницу входа по умолчанию для усиления components / 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));
Компонент кнопки: компоненты / кнопки / 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 из документов по ссылке выше, все еще нужно следовать?