2

I am trying to get a login form to work using the below method. I am using JQuery version 1.12.0 and MVC5. i just create a accounts controller, when the admin login in, he/she can do CRUD functionality, others users can just see the posts and comments and nothings, but the login page not working means when I press Login nothing happens. The page does not refresh. It behaves as is I am clicking nothing this is login view

@model string

@{
  ViewBag.Title = "Login";
 }

 @section ExtraHeaders
  {
  <script src="@Url.Content("~/Scripts/Login.js")" type="text/javascript</script>
<script src="@Url.Content("~/Scripts/SHA256.js")" type="text/javascript</script>
 }

 <form action="@Href("~/Accounts/Login")" method="post" id="loginForm">
  <input type="text" name="name" id="name"/> Name <br />
  <input type="password" name="password" id="password"/> Password <br />
  <input type="hidden"  name="nonce" id="nonce" value="@Model"/>
  <input type="hidden"  name="hash" id="hash" value="hash"/>
  <input type="button" onclick="getPasswordHash('password', 'nonce','hash'); $('#loginForm').submit();" value="Login"/>
 </form>

this is login js file code

function getPasswordHash (passwordElement, nonceElement, hashElement)
{
   var password = $('#' + passwordElement).attr('value');
  var nonce = $('#' + nonceElement).attr('value');
  $('#' + hashElement).attr('value', $.sha256(password + nonce));
  $('#' + passwordElement).attr('value', '');

 }

this is account controller for login

private BlogModel model= new BlogModel();

    public ActionResult Login(string name, string hash)
    {
        if(string.IsNullOrWhiteSpace(hash))

        {
            Random random = new Random();
            byte[] randomData = new byte[sizeof(long)];
            random.NextBytes(randomData);
            string newNonce = BitConverter.ToInt64(randomData, 0).ToString("X16");
            Session["Nonce"] = newNonce;
            return View(model: newNonce);

        }

        Administrator admin = model.Administrators.Where(x => x.Name == name).FirstOrDefault();
        string nonce = Session["Nonce"] as string;
        if(admin == null || string.IsNullOrWhiteSpace(nonce))
        {
            return RedirectToAction("Index", "Posts");

        }
        string computedHash;
        using (SHA256 sha256 = SHA256.Create()) //sha256
        {
            byte[] hashInput = Encoding.ASCII.GetBytes(admin.Password + nonce);
            byte[] hashData = sha256.ComputeHash(hashInput);
            StringBuilder stringBuidler= new StringBuilder();
            foreach(byte value in hashData)
            {
                stringBuidler.AppendFormat("{0:X2}", value);

            }
            computedHash = stringBuidler.ToString();

        }
        Session ["IsAdmin"]= (computedHash.ToLower() == hash.ToLower());
        return RedirectToAction("Index","Posts");
    }


    public ActionResult Logout()
    {
        Session["Nonce"] = null;
        Session["IsAdmin"] = null;
        return RedirectToAction("Index", "Posts");

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

EDIT: getPasswordHash when i right click on its definition, it tell me "failed" either because the caret is already at the definition or because an explicit definition could not be found

Mashhad
  • 23
  • 1
  • 6
  • Why are you computing a hash client-side in the first place? Why not just take out the JavaScript and use a normal `submit` button? – David Jan 19 '16 at 19:12
  • sir i'm beginner and following a video for practice. any help will be appreciated thanks in advance – Mashhad Jan 19 '16 at 19:14

4 Answers4

0

Decorate your action-method using HTTP post attribute

 [HttpPost]
 public ActionResult Login(string name, string hash)
 {
 }

Http get and post more info

Community
  • 1
  • 1
MMM
  • 3,132
  • 3
  • 20
  • 32
  • What difference would this make? All this does is *restrict* the verb to `POST`, but this isn't required in order to use a `POST` in the first place. Non-attribute-decorated action methods still accept `POST` requests. – David Jan 19 '16 at 19:19
0

The simplest approach would be to not use that JavaScript in the first place. It's not accomplishing anything, since you have server-side code to compute the hash anyway. And it's even potentially a security risk, since it exposes the hash computation (including any salt you use) to anyone who wants to see it.

Just remove it entirely and use a normal submit button:

<input type="submit" value="Login"/>

Also, of course, remove this line:

<input type="hidden"  name="hash" id="hash" value="hash"/>

And remove the hash parameter from the action method:

public ActionResult Login(string name)

There's probably more you can remove as well. For example, that "nonce" element and the corresponding model that's being passed to the view in the first place. (It really seems like there are a lot of moving parts involved in functionality that shouldn't be there in the first place.)


Though what's not clear is why your action method isn't accepting the password as a parameter? Normally a login form involves checking a password...

David
  • 208,112
  • 36
  • 198
  • 279
  • sir i'm beginner and following a video for practice. any help will be appreciated thanks in advance thanks – Mashhad Jan 19 '16 at 19:23
  • @Mashhad: Um... ok? Did you have any sort of follow-up to go with that regarding the question and answer here? – David Jan 19 '16 at 19:24
  • i'm following the video, all seems to good but now i'm in problem for login functionality, if i use submit instead of button then it will back to the index and saw a post as anonymous person, then i can not edit or delete post – Mashhad Jan 19 '16 at 19:31
  • @Mashhad: Then you're going to have to debug why that happens. Step through the server-side code in your debugger and see what isn't working as expected. As I mention in my last statement of this answer, it's *very strange* that you're not even *looking at* the password in your server-side code. I would *expect* that a user isn't logged in if the code never checks their password. Maybe you should be sending the password to the server along with the username and comparing the hash of that password to the stored hash. (You should probably also find a better tutorial, this one sounds *awful*.) – David Jan 19 '16 at 19:34
0

If it's the call to getPasswordHash that is causing an error, or something in that function, here's a few things to check:

1) Are both javascript files Login.js and SHA256.js definitely loading?

2) If yes, if you view-source for the page in the browser, does <input type="hidden" name="nonce" id="nonce" value="@Model"/> have a value set? Your controller doesn't seem to set a value for the model getting passed into the view, and given SHA256 references the nonce value, this could be causing a problem.

3) Given that Login.js references SHA256.js, and not the other way around, put the call to SHA256.js above Login.js

Like David says, if this is a tutorial that you're learning from then OK but otherwise it's best doing the password hash at the server and not the client.

Anthony
  • 850
  • 8
  • 20
0

First of all, use MVC3 Jquery 1.5 and SHA256 V1.0 From Alex Weber.

Secondly, the code is defective.

I am also following the "From Zero to Blog" series. At this moment I am debugging the hash generating code because I have no problems logging in.

My problem is it doesn't give me the "delete" and "edit" option after logging in.

While debugging the code this is correct, the 2 hashes

Session["IsAdmin"] = (computedHash.ToLower() == hash.ToLower()); 

from AccountController.cs which are compared in this line aren't the same, and have had completely different values every time.

Geoff James
  • 3,122
  • 1
  • 17
  • 36
  • Hi John, welcome to stackoverflow! You have not posted an answer to the posed question, which is not how stackoverflow works. Please take the tour: http://stackoverflow.com/tour, then you might want to consider creating a new question for your specific problem. – Florian Moser May 20 '17 at 21:03