Authorization of users to actions that use the Authorize attribute

6

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

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

For every time code 401 occurs it redirects to the login page, but I do not know how to do in controller LOGIN to assign access to person.

My problem is this, it redirects to the login, but when I log in it is still not accessible, there is probably something missing from 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");
            }
        }
    }
    
asked by anonymous 18.11.2015 / 17:20

3 answers

1

Let's try to help you a bit more.

In this part of your code, you are just checking to see if a registered user exists in your database with this login and password. But 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 that 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);
        }

In this way you can use the [authorize] attribute as you already do. Remember that you are using FormsAuthentication to perform authentication.

Currently, Microsoft has an excellent Framework to do this, called Asp .Net Identity. It already has the necessary settings for authentication, access control, social networking authentication, and more.

If you want to know more about it, I'll leave some tutorial links about.

Links

18.11.2015 / 20:59
3

You need two Actions one only to return View and in> (checking user data and password) and redirection.

But in your code there are some problems, you do not have these two Actions and also is not performing the 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 the framework to know whether or not it can access Actions that have been decorated with the Authorize attribute. >

To add this cookie in the user's browser you can use the 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));
        }
    }
    
18.11.2015 / 17:51
2

Possibly you are not passing the variables because you did not indicate that it is an Action POST :

[HttpPost]
public ActionResult Login(Usuario usuario)
{
    ...
}
    
18.11.2015 / 17:40