Asp.net React+Redux, tracking a user who has logge

2019-08-17 07:47发布

I've set up an Asp.Net Identity system for my WebAPI using this tutorial: http://www.binaryintellect.net/articles/b957238b-e2dd-4401-bfd7-f0b8d984786d.aspx, everything works great and the only difference is I'm using React+Redux for my frontend which sends action calls to the WebAPI which takes care of user registrations and logging in.

When registering users are created successfully and added to a database, when logging in signInManager.SignIn() returns success so everything is great.

However subsequent calls to other WebAPI actions does not show the user to be authenticated. I'm not sure why this is and can only assume it has to do either with the fact I'm using a WebAPI seperately or my frontend is different.

I've tried using Cookie authentication following this example but it hasn't helped: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x

Another thing I tried was to use a ProxyController on the front end. So React+Redux runs fetch's on the proxy controller actions which will then in turn make the call to the WebAPI. I thought this might work if I use the same HttpClient for all my action calls to the WebAPI (perhaps it preserves some form of state?).

Code below is what I tried:

    HttpClient httpClient;

    [HttpGet("[action]")]
    public async Task<JsonResult> Login(string username, string password)
    {
        HttpResponseMessage responseMessage;
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, 
                "http://localhost:62356/api/mywebapi/login?username=" + username + "&password=" + password);
            responseMessage = await httpClient.SendAsync(request);
        }
        var json = JsonConvert.DeserializeObject(await responseMessage.Content.ReadAsStringAsync());

        return new JsonResult(json);
    }

// api/mywebapi/test tries to confirm through signInManager is user is signed in 
//using: (!signInManager.IsSignedIn(HttpContext.User)) which returns false, // if I 
add an [Authenticate] decorator to the 'Test' action function the below code 
returns a 404...
        [HttpGet("[action]")]
        public async Task<JsonResult> Test()
    {
        HttpResponseMessage responseMessage;
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
                "http://localhost:62356/api/mywebapi/test");

            responseMessage = await httpClient.SendAsync(request);
        }

        dynamic result = new System.Dynamic.ExpandoObject();

        return new JsonResult(result);
    }

Is there something I'm missing from the equation?

0条回答
登录 后发表回答