Я создаю сеть, используя приложение ReactJS + do tnet core MVC. При поиске я получаю только те образцы, которые используют визуальную проверку ios авторизацию по умолчанию (пример: методы JWT).
Я хотел бы использовать настраиваемую аутентификацию с контроллером и mysql db.
ниже мой компонент реакции:
import React from 'react';
export class LoginMN extends React.Component {
static displayName = LoginMN.name;
constructor(props) {
super(props);
this.state = { loading: true, fields: {}, errors: {} };
}
handleValidation() {
let fields = this.state.fields;
let errors = {};
let isFormValid = true;
/***************** Email validation *****************/
if (!fields["email"]) {
isFormValid = false;
errors["email"] = "Email is required";
}
else if (typeof fields["email"] !== "undefined") {
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
isFormValid = false;
errors["email"] = "Enter a valid email id";
}
}
/***************************************************/
/*************** Password validation ***************/
if (!fields["password"]) {
isFormValid = false;
errors["password"] = "Password is required";
}
else if (typeof fields["password"] !== "undefined") {
let pwd = fields["password"];
if (pwd.length < 8) {
isFormValid = false;
errors["password"] = "Enter valid password";
}
}
/***************************************************/
/************* Mobile number validation ************/
if (!fields["phone"]) {
isFormValid = false;
errors["phone"] = "Phone number is required";
}
else if (typeof fields["phone"] !== "undefined") {
let phone = fields["phone"];
if (isNaN(phone)) {
isFormValid = false;
errors["phone"] = "Enter valid phone number";
}
else if(phone.length < 10) {
isFormValid = false;
errors["phone"] = "Phone number should be 10 digits";
}
}
/***************************************************/
this.setState({ errors: errors });
return isFormValid;
}
handleChange(field, e) {
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({ fields });
}
componentDidMount() {
this.getAuthenticationStatus();
}
render() {
return (
<div>
<h2>Login </h2>
<form name="contactform" className="shadow contactform" onSubmit={this.generateOtp.bind(this)}>
<div className="row">
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<span className="input-group-text ">
<i className="fas fa-at text-success"></i>
</span>
<input
type="text"
ref="email"
className="form-control border-0"
placeholder="Email ID*"
id="email"
name="email"
onChange={this.handleChange.bind(this, "email")}
value={this.state.fields["email"]}
/>
</div>
<span style={{ color: "red" }}>
{this.state.errors["email"]}
</span>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<span className="input-group-text">
<i className="fa fa-user-secret text-success"></i>
</span>
<input
type="password"
ref="password"
className="form-control border-0"
name="password"
id="password"
placeholder="Password*"
onChange={this.handleChange.bind(this, "password")}
value={this.state.fields["password"]}/>
</div>
<span style={{ color: "red" }}>
{this.state.errors["password"]}
</span>
</div>
</div>
</div>
<div className="row">
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<span className="input-group-text">
<i className="fa fa-volume-control-phone text-success"></i>
</span>
<input
type="text"
ref="phone"
className="form-control border-0"
name="phone"
id="phone"
placeholder="10 digit phone number*"
onChange={this.handleChange.bind(this, "phone")}
value={this.state.fields["phone"]}/>
</div>
<span style={{ color: "red" }}>
{this.state.errors["phone"]}
</span>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<button className="btn btn-success">Generate OTP</button>
</div>
</div>
</div>
</div>
</form>
<hr />
<form className="shadow hidden">
<div className="row">
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<span className="input-group-text">
<i className="fas fa-key text-success"></i>
</span>
<input type="text" className="form-control border-0" name="otp" id="otp"
placeholder="One time password(OTP) sent to your phone / email*" />
</div>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<div className="input-group shadow bg-white rounded p-3">
<button className="btn btn-danger">Submit</button>
</div>
</div>
</div>
</div>
</form>
</div>
);
}
generateOtp(e) {
e.preventDefault();
if (this.handleValidation()) {
//Check DB
console.log("isAuthenticated=" + this.getAuthenticationStatus());
//call SendOTP method
}
}
async getAuthenticationStatus() {
//IsAuthenticated method is available in Controller
const response = await fetch('IsAuthenticated');
const data = await response.json();
this.setState({ loading: false });
}
}
Вот мой класс контроллера
namespace sampleReactMVC.Controllers
{
[ApiController]
[Route("[controller]")]
public class LoginController : Controller
{
[HttpPost("authenticate")]
public bool IsAuthenticated(string email, string password, string phone)
{
bool isAuthenticated = false;
UserProfile usrProfile = new UserProfile(email, password, phone);
DBConnect myDbConnection = new DBConnect();
//This method checks from mysql db
isAuthenticated = UsersDbAccess.GetAuthenticationStatus(usrProfile, myDbConnection.GetConnection());
usrProfile.SetAuthenticationStatus(isAuthenticated);
return isAuthenticated;
}
}
}
Вопросы:
- Как передавать данные из ReactComponent в контроллер через URL-адрес (/ login / username /)
- Как безопасно передавать данные из ReactComponent в контроллер (для аутентификации, если это через URL, он будет виден)
- Способы передачи данных из ReactComponent в Контроллер и наоборот
Я понимаю C# но реагирую и API / WebAPI для меня впервые.
Пожалуйста, помогите с этой необходимой информацией.