Search code examples
c#blazorasp.net-identityasp.net-core-webapi

Unable to get cookies in blazor web assembly from web api


Please help me I don't know what can be wrong, I've been trying to find something for hours...

I want to have a user login component on the cookie in blazor. I have set the cookies and implemented logged out but I am unable to check that the cookie exist or not in web api code to get information from the cookies to blazor client app.

In web api this is my program.cs

enter image description here

In blazor web assembly app this is my program.cs

enter image description here

Now this is my getcurrentuser in which request.cookies["abc"] works if I consumed it from web api but if I use blazor web assembly to call the web api it doesn't work it is returning null. how can i make this

enter image description here

Updated:

enter image description here

My web api project where i am adding cookie

enter image description here


Solution

  • According to your configuration information, I guess your verification process should be as follows:

    Blazor WebAssembly requests the API for user authentication by sending the user credentials to API.

    For valid credentials, API generates auth cookie and sends it to the client application.

    So after successful authentication of every request from Blazor WebAssembly to API, the auth cookie will be attached to every subsequent request to make the request as authenticated.

    Just from the code you provided, I have no way of knowing how you are setting the cookies, but here is an example: BlazorWasmSocialLoginCookieAuth, I think it will be helpful for you.

    In fact, this example is not complete (the author may have some problems when uploading), you need to create a database and table (Database: BwasmAllCookieAuth Table: User), and then add a default account in the table, and you need to add the corresponding connection string in appsetting.json. I've tested it and it works fine after adding it.

    Your GetCurrentUser method is equivalent to the UserProfileAsync in the example, I read the Cookie in it, it can be obtained:

    var cookies = HttpContext.Request.Cookies[".AspNetCore.Cookies"];
    

    Here is the explanation corresponding to this example, which may help you understand it faster: Blazor WebAssembly Cookie Authentication[.NET 6].