0

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?

2 Answers 2

1

The "with ASP.NET core" does not say much for your issue... What i mean by this: The front client, and the backend .net core, are different things, and one does not affect the other.... Since you are handling auth with cookies on the server, the only thing to do on the client would be to:

  1. On auth response, read the cookie and hold the claims, name, id, role etc etc in the state of your application ( Take a look here )
  2. Make sure that all requests also send out the cookie ( which would be done by default from all browsers anyway.
  3. When routing inside the app, check if the user has the needed claims

Now, since you are using a react app, i would advise the use of JWT tokens, instead of cookies, just so that you enforce statelessness throughout the application, cookies are not great for that. Again, if you where to use JWTs:

  1. The backend is a separate thing, your calls would remain as they are in the API, but they would provide tokens etc etc to the callers, instead of cookies on the response.
  2. Read JWT, store claims in the app state and use the, with routing for example, to check authent/authorization state of calls.
  3. Make sure that tokens are provided in the header of each requests, this is normally done manually from your app, the browsers do not handle this part of communications.

There is also one more key point: Are you building SPA or are you building an mvc solution?? The guide that you pointed out to, revolves around an mvc project and you should not follow the same guidelines for a react app, that is usually a spa... I suggest you take a look on this immediately!

Sign up to request clarification or add additional context in comments.

Comments

0

In my opinion, for a front-end browser-based application talking with a REST API, the most common approach is to go with token-based authentication that relies on OAuth 2.0 protocol to perform the actual issuance of the tokens. Additionally, you should aim to delegate token issuance to a third-party (such as: IdentityServer4) so that you don't need to implement or maintain that part of the system and only need to consume/validate the generated tokens. You could check the following articles:

Authentication and authorization for SPAs

Using SPA (React/Angular) UI with Identity Server 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.