locked
How to share the same Context for both Web API project and MVC Project? RRS feed

  • Question

  • User600651647 posted

    Hi,

    I have a Web API project with Registration and Login methods in the API Account controller and when someone logins in to my website I call the API and get the access token to access other pages.

    I have an MVC Project from which I am calling the same Web API project to login.

    Inside my second MVC Project within the MVCcontroller, I am using Authorize attribute ( [Authorize] ) and also I have to get the user name of the currently logged in User ( HttpContext.Current.User.Identity.Name ).

    Both of them will NOT work just because the person has logged in using a call to API.

    My MVC project can connect to the SAME DATABASE which is connected in the Web API project.

    But, how do I share the same context and user name in both projects?

    Thanks

    Monday, February 8, 2016 11:51 AM

Answers

  • User-782957977 posted

    You can use following code in MVC account controller. Please post to following method from MVC view

    Login Action method - MVC Account Controller

    [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                    var user = await UserManager.FindAsync(model.Email, model.Password);
                    if (user != null)
                    {
    		    /* Use this Web Api token in view if you have direct Web Api call using JQuery/JavaScript from MVC view */
                        Session["Token"] = GetWebApiToken(model.Email, model.Password);
    		    
                        await SignInAsync(user, model.RememberMe);
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
            }

    Code to get Web Api token

    private string GetWebApiToken(string userName, string password)
            {
                 
                using(HttpClient client= new HttpClient())
                {
                    var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", userName ), 
                            new KeyValuePair<string, string> ( "Password", password )
                        };
                    var content = new FormUrlEncodedContent(pairs);
                    // Attempt to get a token from the token endpoint of the Web Api host:
                    HttpResponseMessage response = client.PostAsync("http://localhost:58745/token", content).Result;
                    var result = response.Content.ReadAsStringAsync().Result;
                    // De-Serialize into a dictionary and return:
                    Dictionary<string, string> tokenDictionary =
                        JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                    return tokenDictionary["access_token"];
                }
                
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 11, 2016 4:40 AM

All replies

  • User-782957977 posted

    If you modify MVC login method like this, you can achieve 

            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                    //GetWebApiToken();
                    var user = await UserManager.FindAsync(model.Email, model.Password);
                    if (user != null)
                    {
                        await SignInAsync(user, model.RememberMe);
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
            }

    Tuesday, February 9, 2016 2:08 AM
  • User600651647 posted

    Hi,

    I don't understand what you mean by this.

    The login is happening in Web API project which is hosted on Server 1 and 

    I need the current logged in user in the MVC project which is hosted on Server 2.

    How do I get a model with EmailId in my MVC project?

    Thanks

    Tuesday, February 9, 2016 3:55 PM
  • User-782957977 posted

    My approach will work only if you first login to MVC server first and then send request to Web pi server  from MVC server to get Authentication token.

    Wednesday, February 10, 2016 3:54 AM
  • User600651647 posted

    Hi,

    It will be very helpful if you have any example.

    Thanks

    Wednesday, February 10, 2016 4:27 PM
  • User-782957977 posted

    You can use following code in MVC account controller. Please post to following method from MVC view

    Login Action method - MVC Account Controller

    [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                    var user = await UserManager.FindAsync(model.Email, model.Password);
                    if (user != null)
                    {
    		    /* Use this Web Api token in view if you have direct Web Api call using JQuery/JavaScript from MVC view */
                        Session["Token"] = GetWebApiToken(model.Email, model.Password);
    		    
                        await SignInAsync(user, model.RememberMe);
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
            }

    Code to get Web Api token

    private string GetWebApiToken(string userName, string password)
            {
                 
                using(HttpClient client= new HttpClient())
                {
                    var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", userName ), 
                            new KeyValuePair<string, string> ( "Password", password )
                        };
                    var content = new FormUrlEncodedContent(pairs);
                    // Attempt to get a token from the token endpoint of the Web Api host:
                    HttpResponseMessage response = client.PostAsync("http://localhost:58745/token", content).Result;
                    var result = response.Content.ReadAsStringAsync().Result;
                    // De-Serialize into a dictionary and return:
                    Dictionary<string, string> tokenDictionary =
                        JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                    return tokenDictionary["access_token"];
                }
                
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 11, 2016 4:40 AM