I implemented Authentication and Authorization in my MVC project as https://metanit.com/sharp/aspnet5/15.1.php. I have an Account controller that allows Authentication and Authorization:
public class AccountController : Controller
{
private UsersContext db;
public AccountController(UsersContext context)
{
db = context;
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
User user = await db.Users.FirstOrDefaultAsync(u => u.PhoneNumber == model.PhoneNumber && u.Password == model.Password);
if (user != null)
{
await Authenticate(model.PhoneNumber); // аутентификация
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return View(model);
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterModel model)
{
if (ModelState.IsValid)
{
User user = await db.Users.FirstOrDefaultAsync(u => u.PhoneNumber == model.PhoneNumber);
if (user == null)
{
// добавляем пользователя в бд
db.Users.Add(new User { PhoneNumber = model.PhoneNumber, Password = model.Password });
await db.SaveChangesAsync();
await Authenticate(model.PhoneNumber); // аутентификация
return RedirectToAction("Index", "Home");
}
else
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return View(model);
}
private async Task Authenticate(string phone)
{
// создаем один claim
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, phone)
};
// создаем объект ClaimsIdentity
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
// установка аутентификационных куки
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login", "Account");
}
}
It is saving Authentication data in Cookie. It is working fine. What is the best way to use this in the react-native app?