0
votes

I'm getting an error while trying to login to SharePoint 2013 using Identity Server 4, this is the error "This method can only be called after the authentication event at System.Web.HttpRequest.get_LogonUserIdentity() +258".

The error happens when I host the identity server mvc core app on IIS. when run it from the Visual Studio, it works fine. can someone advise or help.

Edited:

This is the SignIn action in the Account Controller

[HttpGet]
    public async Task<IActionResult> Login(string returnUrl)
    {
        var vm = await _account.BuildLoginViewModelAsync(returnUrl);

        if (vm.IsExternalLoginOnly)
        {
            // only one option for logging in
            return await ExternalLogin(vm.ExternalProviders.First().AuthenticationScheme, returnUrl);
        }
         if(!string.IsNullOrEmpty(Request.Query["culture"])) ViewBag.QueryString = Request.QueryString.Value.Replace("&culture=en", "").Replace("&culture=ar", "") + "&culture=" + Request.Query["culture"];
        else ViewBag.QueryString = Request.QueryString.Value.Replace("&culture=en", "").Replace("&culture=ar", "") + "&culture=en";
        return View(vm);
    }

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model)
    {
        if (ModelState.IsValid)
        {
            // validate username/password against in-memory store
            if (_users.CheckPassword(model.Username, model.Password))
            {
                AuthenticationProperties props = null;
                // only set explicit expiration here if persistent. 
                // otherwise we reply upon expiration configured in cookie middleware.
                if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                {
                    props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    };
                };

                // issue authentication cookie with subject ID and username
                var user = _users.Find(model.Username);
                await HttpContext.Authentication.SignInAsync(user.SubjectId, user.UserName, props);
                // deleteCookie();
              //  HttpContext.Response.Cookies.Append("FedAuth", "", new CookieOptions() { Expires = DateTime.Now.AddDays(-1) });
                // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint
                if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }

                return Redirect("~/");
            }

            ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
        }
        ViewBag.QueryString = Request.QueryString.Value;
        // something went wrong, show form with error
        var vm = await _account.BuildLoginViewModelAsync(model);
        return View(vm);
    }

This is the full Error details

<html><head>
        <title>This method can only be called after the authentication event.</title>
        <meta name="viewport" content="width=device-width">
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><h1>Server Error in '/' Application.<hr width="100%" size="1" color="silver"></h1>

            <h2> <i>This method can only be called after the authentication event.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.InvalidOperationException: This method can only be called after the authentication event.<br><br>

            <b>Source Error:</b> <br><br>

            <table width="100%" bgcolor="#ffffcc">
               <tbody><tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

                  </td>
               </tr>
            </tbody></table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width="100%" bgcolor="#ffffcc">
               <tbody><tr>
                  <td>
                      <code><pre>
[InvalidOperationException: This method can only be called after the authentication event.]
   System.Web.HttpRequest.get_LogonUserIdentity() +5017679
   Microsoft.SharePoint.ApplicationRuntime.SPRequestModuleData.GetRequestData(HttpContext context, String virtualPath, Boolean allowCreate) +203
   Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.InitContextWeb(HttpContext context, SPWeb web) +140
   Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) +842
   Microsoft.SharePoint.Utilities.SPUtility.RedirectValidateInternal(String url, SPWeb web, HttpContext context, Boolean isTrusted) +301
   Microsoft.SharePoint.Utilities.SPUtility.DetermineRedirectUrl(String urlProposed, SPRedirectFlags flags, HttpContext context, SPWeb overrideWeb, String queryString, String&amp; urlRedirect) +736
   Microsoft.SharePoint.Utilities.SPUtility.Redirect(String url, SPRedirectFlags flags, HttpContext context, String queryString) +77
   Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.OnSignedIn(EventArgs eventArgs) +579
   Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request) +736
   Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +324
   Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +139
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +92
</pre></code>

                  </td>
               </tr>
            </tbody></table>

            <br>

            <hr width="100%" size="1" color="silver">

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1087.0

            </font>

    

<!-- 
[InvalidOperationException]: This method can only be called after the authentication event.
   at System.Web.HttpRequest.get_LogonUserIdentity()
   at Microsoft.SharePoint.ApplicationRuntime.SPRequestModuleData.GetRequestData(HttpContext context, String virtualPath, Boolean allowCreate)
   at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.InitContextWeb(HttpContext context, SPWeb web)
   at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
   at Microsoft.SharePoint.Utilities.SPUtility.RedirectValidateInternal(String url, SPWeb web, HttpContext context, Boolean isTrusted)
   at Microsoft.SharePoint.Utilities.SPUtility.DetermineRedirectUrl(String urlProposed, SPRedirectFlags flags, HttpContext context, SPWeb overrideWeb, String queryString, String& urlRedirect)
   at Microsoft.SharePoint.Utilities.SPUtility.Redirect(String url, SPRedirectFlags flags, HttpContext context, String queryString)
   at Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.OnSignedIn(EventArgs eventArgs)
   at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request)
   at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args)
   at Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
--></body></html>
1
Can you post your code please?moritzg
@moritzg I haved added the authentication logic in the question , please let me know if you need more detailsMahmoud Shaaban
The full stack trace of the error would be helpful too!moritzg
I added error details and error full stackMahmoud Shaaban
Ok strange error, I had similar problems when switching between Release and Debug, so I suggest you clean your project, and try to run it locally with Release? And check the configuration differences between Release and Debugmoritzg

1 Answers

0
votes

I have been able to solve the issue by modifying the redirect Url of SharePoint site and removing default.aspx from the url to be http://{{SP Site}}/_trust instead of http://{{SP Site}}/_trust/default.aspx