Authorization of users to actions using the Authorize attribute

Asked

Viewed 647 times

6

I put the [Authorize] in my controllers and I inserted this code:

<authentication mode="Forms">
  <forms loginUrl="/Login/Login" />
</authentication>`

For whenever the 401 code occurs it redirect to the login page, however I do not know how to controller LOGIN to grant access to a person.

My problem is this, it redirects to login, however when login it remains without access, probably missing something in my LOGIN.

Below is my Controller:

  public ActionResult Home()
    {
        return View();
    }

    public ActionResult Login(Usuario usuario)
    {
        if (usuario.Nome == null)
        {
            return View();
        }
        else
        {
            var user = db.Usuario.Where(u => u.Nome == usuario.Nome && u.Senha.Equals(usuario.Senha)).First();

            if (user.Nome.Equals(null))
            {
                ViewBag.Mensagem = "Usuário ou Senha Inválido, tente novamente!";
                return View();
            }
            else
            {
                return RedirectToAction("Home");
            }
        }
    }
  • 1

    How so inform? If the user accesses it is already authorized, no?

  • 1

    I could not understand very well what you meant. Could you elaborate your question better? It would also be interesting for you to improve this title to make it more specific, it will make it easier for other users to find your question if they have the same question.

3 answers

2

Maybe you’re not passing the variables because you didn’t indicate that you’re a Action POST:

[HttpPost]
public ActionResult Login(Usuario usuario)
{
    ...
}

2

You need two Actions one just to return to View of login and another to make the attempt to login (checking user and password data) and redirecting.

But in your code there are some problems, you don’t have those two Actions and also not performing user authentication when the user and password are correct, the authentication process adds a cookie in the user’s browser that will be used by framework to know whether or not he can access Actions which were decorated with the attribute Authorize.

To add this cookie in the user’s browser you can use the method FormsAuthentication.SetAuthCookie. Take a look at the example below where I perform a complete user authentication process.

    public ActionResult SignIn(string returnUrl = "/")
    {
        // Apenas retorna a View login
        return View(new UserSignInViewModel
        {
            ReturnUrl = returnUrl
        });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> SignIn(UserSignInViewModel viewModel, string returnUrl = "/")
    {
        // Retorna a View de login novamente caso exista dados incorretos no model
        if (!ModelState.IsValid)
            return View();

        try
        {
            // Aqui estou procurando no banco por pelo usuário e senha fornecidos, isso aqui é muito específico para esse exemplo, você deverá fazer essa verificação da sua maneira
            var filter = Builders<User>.Filter.Eq(u => u.UsernameUpper, viewModel.Username.ToUpper()) & Builders<User>.Filter.Eq(u => u.Password, viewModel.Password);
            var user = await ZigBlogDb.Users.Find(filter).SingleOrDefaultAsync();

            // Caso eu não encontre retorno a mesma View de login com um erro dizendo que o usuário e/ou a senha estão incorretos
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, Translation.UserSignInError);
                return View();
            }

            // Caso eu encontre adiciono o cookie no navegador do usuário passando o nome do usuário como primeiro argumento, e no segundo argumento eu especifico se esse cookie deverá permanecer além dessa sessão
            FormsAuthentication.SetAuthCookie(user.Username, viewModel.RememberMe);

            // No final eu realizo o redirecionamento
            return Redirect(returnUrl);
        }
        catch (Exception ex)
        {
            return View("Error", new SharedErrorViewModel(ex));
        }
    }
  • This code above belongs to which controller?

  • It’s the code of a controller of login.

  • Look who’s alive :)

1


We’ll try to help you a little more.

In this part of your code, you are only checking if there is a registered user in your database with this login and password. However, at no time do you really "authenticate" the user:

var user = db.Usuario.Where(u => u.Nome == usuario.Nome && u.Senha.Equals(usuario.Senha)).First();

You can change this by simply adding this part to your code:

[HttpPost]
        public ActionResult LogOn(Usuario model, string returnUrl)
        {
            var user = db.Usuarios.First(u => u.Login == model.Login && u.Senha.Equals(model.Senha));

            //verifica se possui usuário
            if (user != null)
            {
                //adiciona cookie de autenticação 
                FormsAuthentication.SetAuthCookie(model.Login, model.LembrarMe);

                //verifica se possui o uma url para retornar ou se está na página logOn
                if (this.Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }



            // Mensagem de erro caso nãoa che usuário
            this.ModelState.AddModelError("", "Login ou senha incorretos");
            return View(model);
        }

This way you can use the attribute [authorize] like you’re already doing. Remembering that you are using the Formsauthentication to perform the authentication.

Currently, Microsoft has an excellent framework to accomplish this, called Asp.Net Identity. It already has the necessary settings for authentication, access control, social network authentication, among other options.

If you want to know more about, I’ll leave some links with tutorials (in English) about.

Links

  • Thanks, I need something simple for now, because this system is supervised internship of the college and I’m on a tight schedule.

  • What would be this part of the model code.Remind me); ?

  • 1

    @J.C.Galhardi keeps the information you want that Rowse remembers that you are logged in, even closing the page. Like "stay connected" from Facebook.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.