0

I have a project with AngularJS and WebApi2 and FormAuthentication. Because I need to import some old code from a WebForms project which uses session to store some user variables, I have to implement Session in WebApi.

In WebConfig I have:

`

 <authentication mode="Forms">
      <forms loginUrl="/index.html" defaultUrl="/Areas/Modeler/modeler.html" name=".ASPXFORMSAUTH" protection="All" cookieless="UseDeviceProfile" slidingExpiration="true" path="/" domain="" requireSSL="false" timeout="600" enableCrossAppRedirects="false">
      </forms>
</authentication>
<authorization>
        <allow users="*" />
</authorization>
<machineKey validationKey="xxxxx" decryptionKey="xxxxxx" validation="SHA1" />
</system.web>
<location path="Scripts">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>
<location path="~/Authenticate">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

`

I made the following changes in Global.asax.cs to implement Session:

`

public override void Init()
        {
            this.PostAuthenticateRequest += Application_PostAuthorizeRequest;
            base.Init();
        }
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        }
protected void Application_PostAuthorizeRequest(object sender, EventArgs e)
        {
            var url = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
            var auth = Context.Request.IsAuthenticated;
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }`

After user inputs his name and password, I call a post method ~/Authenticate/Login.

In chrome browser network tab I can see next two line: Login Method: POST, Status 302 Login Method GET, Status 405 For first call:

Remote Address:[::1]:52966 Request URL:http://localhost:52966/Authenticate/Login Request Method:POST Status Code:302 Found Response Headers view source Content-Length:166 Date:Thu, 14 May 2015 13:11:24 GMT Location:/(S(tdd41h23pms5lllzyro1hltq))/Authenticate/Login Server:Microsoft-IIS/8.0 X-Powered-By:ASP.NET X-SourceFiles:=?UTF-8?B?RDpcUHJvamVjdH..............=?= Request Headers view source Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8,ro;q=0.6 Connection:keep-alive Content-Length:44 Content-Type:application/json;charset=UTF-8 Cookie:PHPSESSID=d5djbkgs7ttui073jl04mg6st3; __AntiXsrfToken=97b6e321343944a89ade4acc098305bd; ASP.NET_SessionId=2ggakcj1qxtewgsrh5qvtw40; _session_id=BAh7B0kiD3Nlc3Npb25faW....; .AspNet.ApplicationCookie=GcQUqnFHbPaX...; UserPassword=password; UserName=admin; .ASPXFORMSAUTH=7B15EE3DE... DNT:1 Host:localhost:52966 Origin:http://localhost:52966 Referer:http://localhost:52966/index.html User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Request Payload view source {userName: "admin", userPassword: "password"}

The question is : Why the call to Login is redirected? In method Application_PostAuthorizeRequest from Global.ascx.cs ai check Context.Request.IsAuthenticated and is true.

Bogdan
  • 656
  • 15
  • 25

1 Answers1

1

The redirect comes from the configuration. You have configured both a loginUrl and defaultUrl. This is where the user will be sent before and after authentication respectively.

Frank Witte
  • 466
  • 5
  • 17
  • The problem doesn't exist if I don't make changes for using session in Webapi. And this is the way to configure Form Authentication in web.config. – Bogdan May 25 '15 at 06:39
  • Your question was "why the call to Login is redirected?". My answer is because you have "index.html" configured as login page. So when you try to access /Authenticate/login you are redirected to "index.html" if you are not authenticated yet. This might be a seperate problem from the session issue. – Frank Witte May 25 '15 at 07:52
  • Ok. then why is not happen same way when I don't use session? In this case, web api method it's executed with status code 200. – Bogdan May 25 '15 at 08:04
  • And The method Login is decarated with attribute [AllowAnonymous], and in web.config I have: – Bogdan May 25 '15 at 08:08
  • I think, is no need to be authenticate to access the webapi method Login – Bogdan May 25 '15 at 08:09
  • Maybe the session should be conditionally set like in http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api. – Frank Witte May 25 '15 at 08:17
  • I know, the article, but the problem it's happend when is a Webapi call. And also: I don't make other kind of calls to server, so I don't think I need to put condition for webapi call.. – Bogdan May 25 '15 at 08:21
  • Is it possible to upload a sample project to play around with? – Frank Witte May 25 '15 at 08:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78755/discussion-between-bogdanim-and-frank-witte). – Bogdan May 26 '15 at 07:41