spec icon indicating copy to clipboard operation
spec copied to clipboard

Cookie authorization

Open LykRepchatiy opened this issue 1 year ago • 3 comments

Hello!

First of all, I want to thank you for your package. It turned out to be very convenient and flexible!

Problem

I’ve encountered a problem with adding security using cookies. I’m working on a platform that implements session-based authorization. In order to make a request from the Swagger page, it’s necessary to enter the session_id in the Authorize field. However, it isn’t being saved in a cookie, and as a result, the requests return an Unauthorized error.

However, if I log in to my platform, the browser saves the cookie with the session_id, and the requests on the Swagger page work correctly.

Before using cookies, I was using bearer security, and everything worked perfectly.

I’m using the gorilla/mux router, and I created a new OpenAPI generator as follows.

...
	generatorOpenAPI = muxopenapi.NewRouter(router,
		option.WithTitle("Title"),
		option.WithOpenAPIVersion("3.1.0"),
		option.WithVersion(1.0.0),
		option.WithDescription("some description"),
		option.WithServer(server),
		option.WithSecurity("cookie", option.SecurityAPIKey("session_id", "cookie")),
		option.WithContact(
			openapi.Contact{
				Name:  "My Team",
				URL:   "http://example.com",
				Email: "[email protected]",
			}),
		option.WithSwaggerUI(
			ui.SwaggerUI{
				Layout: "StandaloneLayout",
			}),
	)
...

Then I define a HandleFunc with a description for the OpenAPI page and specify the same security type as in NewRouter.

...
    v1.HandleFunc("/platforms", rest.getPlatforms()).Methods(http.MethodGet).With(
		option.Summary("Get platforms"),
		option.Tags(tagExperiments),
		option.Security("cookie"),
		option.Response(http.StatusOK, new([]entity.PlatformObject), option.ContentDescription(success)),
		option.Response(http.StatusBadRequest, responseString, option.ContentDescription(invalidRequest)),
		option.Response(http.StatusUnauthorized, responseString, option.ContentDescription(unauthorized)),
		option.Response(http.StatusInternalServerError, responseString, option.ContentDescription(internalServerError)),
	)
...

After resurch the documentation and the package’s source code, I still can’t determine whether it’s my mistake or a bug in the package. I’d be very glad if you could help!

LykRepchatiy avatar Oct 21 '25 07:10 LykRepchatiy

Hi @LykRepchatiy , i think it need custom config from swagger ui, you can adjust config like this

option.WithSwaggerUI(ui.SwaggerUI{
		Layout: "StandaloneLayout",
		UIConfig: map[string]string{
			"requestInterceptor": `(req) => {
				req.credentials = 'include';
				return req;
			}`,
			"persistAuthorization": "true",
		},
	}),

akfaiz avatar Oct 21 '25 13:10 akfaiz

Yes, it helped. Thank you so much!

LykRepchatiy avatar Oct 22 '25 12:10 LykRepchatiy

You're welcome

akfaiz avatar Oct 22 '25 12:10 akfaiz