locked
SignInManager.SignInAsync Throws error 'No owin.Environment item was found in the context.' RRS feed

  • Question

  • User1647210049 posted

    I am trying to <g class="gr_ gr_13 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="13" data-gr-id="13">login</g> the user without his password. I am using Microsoft FaceAPI to detect the user face and auto <g class="gr_ gr_12 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="12" data-gr-id="12">signin</g>.

    For <g class="gr_ gr_14 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="14" data-gr-id="14">that</g> once I confirm the user identity, I want to make the <g class="gr_ gr_9 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="9" data-gr-id="9">signin</g> and redirect <g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="10" data-gr-id="10">user</g> to <g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="11" data-gr-id="11">home</g> screen.

    I am fetching the Application User from <g class="gr_ gr_15 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="15" data-gr-id="15">database</g> based on the Identity I receive from Face API. And When I try to call the

    SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

    It throws <g class="gr_ gr_24 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="24" data-gr-id="24">error</g> like 'No <g class="gr_ gr_23 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="23" data-gr-id="23">owin</g><g class="gr_ gr_25 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="25" data-gr-id="25">.Environment</g> item was found in the context.'

    For the <g class="gr_ gr_27 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="27" data-gr-id="27">error</g> I am getting I have already tried to add the Startup file path in the web.config file like below

    <add key="owin:AppStartup" value="FaceRecognisation.Web.Startup, FaceRecognisation.Web" />
    <add key="owin:AutomaticAppStartup" value="true"/>

    But that also does not solve the issue.

    In AccountController.cs

    if (identifiedFace.Candidates.Count > 0 && identifiedFace.Candidates.FirstOrDefault().Confidence > 0.5)
    {
        UserFaceManager userFaceManager = new UserFaceManager();
        var user = userFaceManager.FindUserByPersonId(identifiedFace.Candidates.FirstOrDefault().PersonId);
    
        if (user != null)
            SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    }

    Please help me to get rid of the error 'No <g class="gr_ gr_37 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="37" data-gr-id="37">owin</g><g class="gr_ gr_38 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="38" data-gr-id="38">.Environment</g> item was found in the context.'

    Monday, April 1, 2019 2:09 PM

Answers

  • User1647210049 posted

    I Have confirmed, Its the Event Handler, which is causing the issue. If I call it outside the Event Handler then it is working fine.

    Finally, I have implemented it like below

    public async Task<ActionResult> IdentifyUserFaceNew(string userPhoto)
            {
                byte[] imageBytes = Convert.FromBase64String(userPhoto);
    
                FaceLoginResponse faceLoginResponse = new FaceLoginResponse();
    
                faceApiManager = await FaceApiManager.CreateInstanceAsync();
    
                var result = await faceApiManager.IdentifyFace(imageBytes);
                if (result.IdentifiedFaces.Count > 0)
                {
                    var identifiedFace = result.IdentifiedFaces.FirstOrDefault();
                    if (identifiedFace.Candidates.Count > 0 && identifiedFace.Candidates.FirstOrDefault().Confidence > 0.5)
                    {
                        UserFaceManager userFaceManager = new UserFaceManager();
                        var IdentifiedUser = userFaceManager.FindUserByPersonId(identifiedFace.Candidates.FirstOrDefault().PersonId);
                        if (IdentifiedUser != null)
                        {
                            await SignInManager.SignInAsync(IdentifiedUser, isPersistent: false, rememberBrowser: false);
                            faceLoginResponse.Error = "";
                            faceLoginResponse.RedirectUrl = Url.Action("Index", "Home");
                            return Json(faceLoginResponse);
                        }
                    }
                }
                faceLoginResponse.Error = "Not able to identify your face. Kindly do login using your username and password";
                faceLoginResponse.RedirectUrl = "";
                return Json(faceLoginResponse);
            }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 2, 2019 12:34 PM

All replies

  • User-893317190 posted

    Hi pateldipen_92 ,

    Do you have a startup class at your application's root path. It looks like this.

    [assembly: OwinStartup(typeof(WebFormCases2.Startup))]
    
    namespace WebFormCases2
    {
        public class StartupBack
        {
            public void Configuration(IAppBuilder app)
            {
    
                // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
                app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);
                app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
                app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
                app.UseCookieAuthentication(
                    new CookieAuthenticationOptions
                    {
                        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                        LoginPath = new PathString("/login.aspx")
                                       }
                    );
    
    
            }
        }
    }

    If you have 

      <appSettings>
      <add key="owin:AutomaticAppStartup" value="false" />
    
      </appSettings>

    please remove it.

    Please refer to https://stackoverflow.com/questions/18232549/no-owin-environment-item-was-found-in-the-context

    Also refer to this for a  helloworld  guide  https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/introduction-to-aspnet-identity

    Best regards,

    Ackerly Xu

    Tuesday, April 2, 2019 2:06 AM
  • User1647210049 posted

    Hi Ackerly Xu

    Thanks for taking out time to reply on my issue. I have  Startup.cs file already present at the project's root level. And it contains all the stuff which is mentioned by you.

    I don't have added this in <g class="gr_ gr_251 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="251" data-gr-id="251">web</g>.config file.

    <add key="owin:AutomaticAppStartup" value="false" />

    The thing is If I do register then, there it is working fine. There also it is directly <g class="gr_ gr_323 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="323" data-gr-id="323">Signin</g> the user after successful registration by calling SignInManager.SignInAsync method. 

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
                if (ModelState.IsValid)
                {
                    //Person person = await CreatePersonGroupPerson(model);
                    //var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PersonName = model.PersonName, PersonId = person.PersonId };
    
                    var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PersonName = model.PersonName };
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        UserFaceManager userFaceManager = new UserFaceManager();
                        userFaceManager.User = user;
                        Person person = await CreatePersonGroupPerson(model, user);
                        await userFaceManager.UpdateUserPersonId(person.PersonId);
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    
                        // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
    
                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
    }

    But the Same thing when I do <g class="gr_ gr_387 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="387" data-gr-id="387">using</g> below code it is throwing error while calling SignInManaer.SignInAsync method.

    [AllowAnonymous]
    public async Task<ActionResult> IdentifyUserFace()
    {
                int actualCallCounter = 0, currentCallCounter = 0;
    
                faceApiManager = await FaceApiManager.CreateInstanceAsync();
    
                grabber = new FrameGrabber<LiveCameraResult>();
    
                // Set up a listener for when we acquire a new frame.
                grabber.NewFrameProvided += (s, e) =>
                {
                    Console.WriteLine("New frame acquired at {0}", e.Frame.Metadata.Timestamp);
                };
    
                // Set up a listener for when we receive a new result from an API call. 
                grabber.NewResultAvailable += (s, e) =>
                {
                    if (e.TimedOut)
                        Console.WriteLine("API call timed out.");
                    else if (e.Exception != null)
                        Console.WriteLine("API call threw an exception.");
                    else
                    {
                        if (e.Analysis.IdentifiedFaces.Count > 0)
                        {
                            StopCameraProcessing().Wait();
                            var identifiedFace = e.Analysis.IdentifiedFaces.FirstOrDefault();
                            if (identifiedFace.Candidates.Count > 0 && identifiedFace.Candidates.FirstOrDefault().Confidence > 0.5)
                            {
                                UserFaceManager userFaceManager = new UserFaceManager();
                                var user = userFaceManager.FindUserByPersonId(identifiedFace.Candidates.FirstOrDefault().PersonId);
                                
                                if (user != null)
                                    SignInManager.SignInAsync(user , isPersistent: false, rememberBrowser: false);
                            }
                        }
                    }
                    actualCallCounter++;
                    if (actualCallCounter == 3)
                        StopCameraProcessing().Wait();
                };
    
                // Tell grabber when to call API.
                grabber.TriggerAnalysisOnInterval(TimeSpan.FromMilliseconds(3000));
                
                grabber.AnalysisFunction = faceApiManager.IdentifyFace;
    
                // Start running in the background.
                grabber.StartProcessingCameraAsync().Wait();
    
                return Json("Face Identification Processing Started");
    }

    Regards,

    Dipen

    Tuesday, April 2, 2019 7:24 AM
  • User-893317190 posted

    Hi Dipen Patel,

    How do you get the SignInManager? Do you get it through OwinContext?

    HttpContext.GetOwinContext().Get<ApplicationSignInManager>()

    You could also refer to the link below to learn about SignInManager https://stackoverflow.com/questions/38451636/signinmanager-what-it-is-and-how-when-to-use

    If this still could not solve your problem, because your problem relates to  MicroSoft face api, maybe there is something wrong with the way you use microsoft face api I suggest you could post to stackoverflow https://stackoverflow.com/

    Best regards,

    Ackerly Xu

    Tuesday, April 2, 2019 9:51 AM
  • User1647210049 posted

    Hi Ackerly Xu,

    My SignInManager and UserManager looks like 

    public ApplicationSignInManager SignInManager
            {
                get
                {
                    return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
                }
                private set
                {
                    _signInManager = value;
                }
            }
    
            public ApplicationUserManager UserManager
            {
                get
                {
                    return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                }
                private set
                {
                    _userManager = value;
                }
            }

    They are the default which was gets created using the MVC Project template. And I don't think that there is any role of Face API. 

    Is it possible that I am calling SignInManager from the Eventhandler, which is causing the issue?

    Tuesday, April 2, 2019 10:00 AM
  • User1647210049 posted

    I Have confirmed, Its the Event Handler, which is causing the issue. If I call it outside the Event Handler then it is working fine.

    Finally, I have implemented it like below

    public async Task<ActionResult> IdentifyUserFaceNew(string userPhoto)
            {
                byte[] imageBytes = Convert.FromBase64String(userPhoto);
    
                FaceLoginResponse faceLoginResponse = new FaceLoginResponse();
    
                faceApiManager = await FaceApiManager.CreateInstanceAsync();
    
                var result = await faceApiManager.IdentifyFace(imageBytes);
                if (result.IdentifiedFaces.Count > 0)
                {
                    var identifiedFace = result.IdentifiedFaces.FirstOrDefault();
                    if (identifiedFace.Candidates.Count > 0 && identifiedFace.Candidates.FirstOrDefault().Confidence > 0.5)
                    {
                        UserFaceManager userFaceManager = new UserFaceManager();
                        var IdentifiedUser = userFaceManager.FindUserByPersonId(identifiedFace.Candidates.FirstOrDefault().PersonId);
                        if (IdentifiedUser != null)
                        {
                            await SignInManager.SignInAsync(IdentifiedUser, isPersistent: false, rememberBrowser: false);
                            faceLoginResponse.Error = "";
                            faceLoginResponse.RedirectUrl = Url.Action("Index", "Home");
                            return Json(faceLoginResponse);
                        }
                    }
                }
                faceLoginResponse.Error = "Not able to identify your face. Kindly do login using your username and password";
                faceLoginResponse.RedirectUrl = "";
                return Json(faceLoginResponse);
            }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 2, 2019 12:34 PM
  • User-893317190 posted

    Hi pateldipen_92,

    Could you please mark your answer as marked so that the answer could be easily found ?

    Thank you pateldipen_92.

    Best regards,

    Ackerly Xu

    Wednesday, April 3, 2019 1:05 AM