Search code examples
asp.net-mvcwindows-authentication

MVC 4 Windows Authentication


I'm relatively new to MVC, I need to retrieve username and pass it to my company library that checks for user credential.

Web.config

<authentication mode="Windows" />
  <authorization>
    <allow users="*"/>
    <deny users="?"/>
  </authorization>

Controller

[Authorize]
    public class MVCAuthen : Controller
    {
        public string GetCredentials()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            string credential = library.Getcredential(userName);

        return credential;
    }
}

My question is I keep getting blank when I try to retrieve username. Can someone tell me what I'm doing wrong or how I retrieve username?
Note: I'am trying to do this locally since I'm trying to debug it.


Solution

  • First you should be using a Internet Application or Intranet Application template.

    Then on the web.config you should comment or remove the forms authentication and use the windows authentication. Something like this:

    <--
    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    -->
    
    <authentication mode="Windows" />
    

    And add this in the 'appSettings'

    <appSettings>
        <add key="autoFormsAuthentication" value="false" />
        <add key="enableSimpleMembership" value="false"/>
    </appSettings>
    

    Now go to you solution explorer, right click the project and go to properties. There you must change Windows Authentication to enabled.

    If you do not want to allow any anonymous access you may disable Anonymous Authentication too.

    Once that is done you can add the [Authorize] on any Controller or Action.

    Then you should be able to login with your windows password.

    If you are able to login and view the page then you can retrieve the user name like this.

    var username = HttpContext.User.Identity.Name;