alexedwards / scs

HTTP Session Management for Go
MIT License
2.09k stars 166 forks source link

Support API tokens #100

Closed maja42 closed 3 years ago

maja42 commented 3 years ago

Is there a way to support API tokens? My application has two kinds of authentication: via login/logout and via API-Tokens.

The login/logout part is working perfectly fine with scs, but I'm not able to add support for API-Tokens. Callers would only set an api-key header without any cookie/session information. So I need to add a custom handler/middleware that extracts that API-Key, checks if there is already a session for that key and re-use it the session. If there is no such session, I would perform a login/authentication RPC and create a new session with the returned user information.

maja42 commented 3 years ago

The easiest way would probably be to expose the token generator generateToken() (string, error). Add the context as a parameter, and allow users to provide an alternative implementation.

restourgie commented 3 years ago

I hope you are aware that an api token is significantly less secure than a cookie. Any script running in the browser that came from the same origin (meaning same scheme,hostname and port) will be able to access this token. If you have no content security policy setup, any malicous script will be able to send the token to any evil server.

alexedwards commented 3 years ago

@maja42 I don't want to expose generateToken() --- this function is fundamental to the security of SCS and I don't want to provide users with a 'footgun' by making it overridable.

I'm not 100% clear on what your needs are, but I think it should be possible to achieve what you want with some custom LoadAndSave() middleware that implements the exact logic that you need.

There's a gist here which provides an example of using custom LoadAndSave() middleware with SCS: https://gist.github.com/alexedwards/cc6190195acfa466bf27f05aa5023f50. The example demonstrates setting/getting the session token via a HTTP header (rather than a cookie), but you should be able to use the same general pattern to implement your custom business logic.

jakobmaier commented 3 years ago

Thanks for the responses. We already switched from REST to gRPC a while back, where we handle authentication via authToken-headers instead of cookies. So this is not an issue for me anymore.

jakobmaier commented 3 years ago

Regarding security: i don't think there's that much difference to cookies. For headers, you can set the CSPolicy so that malicious script's (that aren't caught by CORS) can't access the data. But with cookies, you also need to be cautious. You need to configure them correctly (don't allow access from JavaScript, or http) and also add additional headers for CSRS/XSRS protection. They contain a lot of implicit logic that's easy to forget or get wrong.