2

I know that many people might not agree with this implementation but I am looking to store a jwt inside a http-only container to prevent javascript access to the token. The .NET application retrieves a Jwt from an Identity Server once a user is authenticated. I then want to create a http only cookie and store the jwt within, with it then being sent to the api for authorization.

I wanted to ask how I can send this cookie to the api and also how to get the api to access the jwt within the cookie and authenticate using the Identity Server (I know that I can use the introspection endpoint on the Identity Server to check if the jwt is valid).

I am currently attempting to use RestSharp to send the request from the application:

var oClient = new RestClient("http://localhost:52298/stockcontrol/availablestock");
            var oContainer =  new CookieContainer();
            var oRequest = new RestRequest();
            oRequest.Method = Method.GET;

            var oCookie = new Cookie("Jwt", sJwt) { HttpOnly = true, Expires = DateTime.Now.AddMinutes(10), Domain = "test" };

            oContainer.Add(oCookie);
            oClient.CookieContainer = oContainer;
            

            var oResponse = oClient.Execute(oRequest);

This is the code I am attempting to use to authenticate the jwt on the api:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                Provider = new CookieAuthenticationProvider()
                {
                    OnValidateIdentity = async context =>
                    {
                        if (context?.Identity?.IsAuthenticated ?? false)
                        {
                            var accessToken = context?.Identity?.Claims?.FirstOrDefault(x => x.Type == "access_token")?.Value;
                            if (accessToken == null)
                            {
                                context?.RejectIdentity();
                            }
                            else
                            {
                                var client = new IntrospectionClient(
                                        sISUrl + "connect/introspect",
                                        sISClientName,
                                        sISClientSecret); // auth as scope, not client!
                                var validationResult = await client.SendAsync(new IntrospectionRequest()
                                {
                                    Token = accessToken
                                });

                                if (validationResult.IsError || !validationResult.IsActive)
                                {
                                    context?.RejectIdentity();
                                }
                            }
                        }
                    }
                }
            });
GWilkinson
  • 107
  • 1
  • 11

0 Answers0