gpt4 book ai didi

javascript - React JS - 如何通过获取语句验证凭据

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:04 25 4
gpt4 key购买 nike

我的目标是创建一个运行 json Rest 服务的 React JS 登录页面。在 Postman 中,当我输入服务的 URL 时,将其设置为以 POST 方式运行并在正文中输入以下 JSON:{用户名:“我的用户名”,密码:“我的密码”}...返回 token 。所以在我的 fetch 子句中,我使用 JSON.stringify 将用户名和密码传递给服务器。

我刚开始使用 Fetch with react,所以我的问题是,如何开始对各种用户进行身份验证,仅使用 react JS with fetch?我假设,我要在我的 Fetch 子句的第二个 then 内编写我的逻辑?

目前,我的页面接受任何凭据,并在点击提交按钮后将用户引导至登录页面。我有一个包含 fetch 的函数,现在在单击 onSubmit 按钮后调用 fetch 函数,它现在获取 token 。

这是我的代码:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './Login.css';
import { withRouter } from 'react-router-dom';

class Login extends Component {

constructor() {
super();
this.state = {
data: [],
username: "",
password: "",
token: "",
};
} //end constructor

componentWillMount() {
}

componentDidMount() {
this.fetchData();
}

fetchData() {
fetch('http://theapi/api/auth', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
username: 'myUserName',
password: 'myPassword',
Authorization: 'TheReturnedToken',
})
}) /*end fetch */
.then(results => results.json())
.then(data => this.setState({ data: data })

)
}

//request the token
requestAccessToken(data) {
const loginInfo = '${data}&grant_type=password';
return fetch('${API_URL}Token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
body: loginInfo,
})
.then((response) => response.json());
}

//authenticate request
requestUserInfo(token) {
return fetch('${API_URL}api/participant/userinfo', {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ${token}',
}),
})
.then((response) => response.json());
}

change = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}; //end change

onSubmit = (e) =>{
this.fetchData();
e.preventDefault();
//console.log(this.state);
this.setState({
username: "",
password: "",
});

this.props.history.push('/landing');
};

render() {
console.log(this.state.data);
return (
<div>
<div className="loginContainer">
<h2>Member Login</h2>
<form>
<input
id="username"
name="username"
placeholder="User Name"
value={this.state.username}
onChange={e => this.change(e) }
className="form-control"
/> <br />

<input
id="password"
name="password"
type="password"
placeholder="Password"
value={this.state.password}
onChange={e => this.change(e) }
className="form-control"
/> <br />

<button onClick={e => this.onSubmit(e)} className="btn btn-primary">Submit</button>
</form>
</div>
</div>
);
}
}

export default withRouter(Login);

如何开始让我的表单对不同的用户进行身份验证?基本上,我试图让我的页面接受用户名和密码,如果两者匹配,然后将用户路由到登录页面。

最佳答案

不要将您的授权 token 放在正文中。把它放在标题中。第一个函数将传入用户名、密码和身份验证类型(即 grant_type=password)。然后我的第二个函数将使用它来验证请求。不再需要传递任何用户信息,因为我的 api 根据传入的 token 知道谁在请求。当前文档 OAuth 2.0 is here ,您可以找到有关使用 header 与 fetch at Mozilla's fetch documentation 的更多信息.

// request the token
// subscribe to this event and use the returned json to save your token to state or session storage
export function requestAccessToken(data) {
const loginInfo = `${data}&grant_type=password`;
return fetch(`${API_URL}Token`, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: loginInfo,
})
.then((response) => response.json());

// in your case set state to returned token
}

// use said token to authenticate request
export function requestUserInfo(token) {
return fetch(`${API_URL}api/participant/userinfo`, {
method: 'GET',
headers: new Headers({
Authorization: `Bearer ${token}`,
}),
})
.then((response) => response.json());
}

我还建议:

  1. 从 thunk 或 saga 调用 fetch,但这超出了问题的范围。

  2. 无需将您的 token 放在隐藏字段中。顺便说一句,这仍然是可以访问的。只是保持它的状态。您还可以采取其他措施来稍微保护它,但这也不在讨论范围之内。

关于javascript - React JS - 如何通过获取语句验证凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com