为你的 React 应用添加一个简单的身份验证
报名
Okta 仪表板
注册你的 React 应用程序
启动你的代码编辑器
创建登录组件
创建注销函数
恭喜!🎉
今天,我将向您展示如何在 React 应用程序中添加一个简单的身份验证,该身份验证使用 Okta 的身份验证功能。Okta 是一个用户管理系统,可用于基于多种语言或框架构建的多个应用程序。
它类似于 Auth0。您可以在多个应用程序中使用它,甚至可以将它用于基于不同语言和平台构建的应用程序。Okta
目前支持以下语言:
- 安卓
- 角度
- iOS
- Java
- 。网
- Node.js
- PHP
- 反应
报名
在将 Okta 集成到你的 React 应用程序中之前,你需要一个 Okta 开发者账号。现在就创建你的免费账号吧!
免费 Okta 开发者账号
Okta 仪表板
创建免费帐户后,您将被重定向到仪表板。您注意到仪表板上的组织 URL 了吗?您的应用程序需要它。仪表板还包含用户指标和系统日志,显示所有活动。
注册你的 React 应用程序
现在是时候注册你的 React 应用程序了。点击仪表板上的“应用程序”链接。
- 点击添加应用程序
- 选择单页应用程序
- 在名称字段中为您的应用添加名称
现在,你需要编辑Base URI 的字段。我假设你在本地服务器上使用 create-react-app。
http://localhost:3000
与登录重定向 URI 相同并单击完成。
http://localhost:3000/implicit/callback
现在您的应用程序已注册并且您将获得一个客户端 ID。
启动你的代码编辑器
- 导航到您的项目文件夹
- 添加必要的包
yarn add react-router-dom @okta/okta-react @okta/signin-widget
为了这个例子,我们假设你的反应应用程序有三个页面,它们应该在私有路由中,并且只有授权用户才能访问这些路由。
/主页
/用户
/订单
创建登录组件
在您的组件文件夹中创建一个名为auth的新文件夹,并使用以下代码创建一个名为 Login.js 的新文件。
*Login.js*
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import OktaSignInWidget from './SigninWidget';
import { withAuth } from '@okta/okta-react';
export default withAuth(class Login extends Component {
constructor(props) {
super(props);
this.state = {
authenticated: null
};
this.checkAuthentication();
}
async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
this.setState({ authenticated });
this.props.history.push('/home')
}
}
componentDidUpdate() {
this.checkAuthentication();
}
onSuccess = (res) => {
if (res.status === 'SUCCESS') {
return this.props.auth.redirect({
sessionToken: res.session.token
});
} else {
// The user can be in another authentication state that requires further action.
// For more information about these states, see:
// https://github.com/okta/okta-signin-widget#rendereloptions-success-error
}
}
onError = (err) => {
console.log('error logging in', err);
}
render() {
if (this.state.authenticated === null) return null;
return this.state.authenticated ?
<Redirect to={{ pathname: '/' }}/> :
<OktaSignInWidget
baseUrl={this.props.baseUrl}
onSuccess={this.onSuccess}
onError={this.onError}/>;
}
});
接下来,您需要在同一个auth目录中使用以下代码创建一个名为SigninWidget的新文件。
*SigninWidget.js*
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import OktaSignIn from '@okta/okta-signin-widget';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
class SigninWidget extends Component {
componentDidMount() {
const el = ReactDOM.findDOMNode(this);
this.widget = new OktaSignIn({
baseUrl: this.props.baseUrl,
authParams: {
pkce: true
},
});
this.widget.renderEl({el}, this.props.onSuccess, this.props.onError);
}
componentWillUnmount() {
this.widget.remove();
}
render() {
return <div />;
}
};
export default SigninWidget
下一步是更新路由文件。以下是我的 Okta 实现示例。将私有路由包装在SecureRoute组件中,并将客户端 ID和颁发者替换为你在 Okta 开发者控制台中获取的凭证。
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Order from "./pages/Order.js";
import Home from "./pages/Home.js";
import Users from "./pages/Users.js";
import Login from "./components/auth/Login";
import { Security, SecureRoute, ImplicitCallback } from "@okta/okta-react";
function onAuthRequired({ history }) {
history.push("/login");
}
const AppRoute = () => (
<Router>
<Security
issuer="https://dev-944example.okta.com/oauth2/default" //Replace with your ORG URI.
clientId="0oa1ws12avokObj45C357example" //Replace with your own client id
redirectUri={window.location.origin + "/implicit/callback"}
onAuthRequired={onAuthRequired}
>
<SecureRoute exact path="/orders" component={Order} />
<SecureRoute exact path="/users" component={Users} />
<Route exact path="/" component={Home} />
<Route
path="/login"
render={() => <Login baseUrl="https://dev-968924.okta.com" />}
/>
<Route path="/implicit/callback" component={ImplicitCallback} />
</Security>
</Router>
);
export default AppRoute;
创建注销函数
这是最后一步。你需要在 home.js 文件或根文件中创建一个注销按钮,该按钮在用户登录后呈现给用户,并且不要忘记将你的函数包装在withAuth中以使用auth属性。
import { withAuth } from "@okta/okta-react";
import Breadcrumb from './breadcrumb.js'
class Home extends Component {
logout = async () => {
this.props.auth.logout("/");
};
render() {
return (
<>
<Breadcrumb home="Logout" click={this.logout} />
</>
);
}
}
export default withAuth(Home);
恭喜!🎉
如果你成功读到这里,我希望你已经成功地将 Okta 身份验证集成到你的 React 应用程序中。如果你遇到任何问题,请在下方留言。我会帮你解决。
这是我在 dev.to 上的第一篇文章。实际上,这是我的第一篇博文。所以,如果您没能完全理解我的技巧,我深表歉意。我很快就会带着新文章回来。
谢谢你!
文章来源:https://dev.to/ajinkabeer/add-a-simple-authentication-to-your-react-application-2lcc