I'd like to observe the outcome of the Authenticat...
# ktor
I'd like to observe the outcome of the Authentication feature and set a header accordingly so that the front-end can keep track of whether or not the back-end thinks that there is an authenticated user. (I can't just rely on 401, etc, because some endpoints work with and without an authenticated user.) I can set response headers inside a `SessionAuthenticationProvider`'s
, but that only applies when a session is present, so it won't get hit on a request with no session or an invalid session cookie. What would be a better place to apply the header that can access
or equivalent, yet will also get called on requests without sessions, etc?
Not sure if I understand the question. I recently had to implement a route using JWT that should produce a meaningful output with and without authentication (instead of a 401 if no authentication is provided). I have proposed this: https://github.com/ktorio/ktor/compare/authenticate.optional Maybe not the final design, but at least a proposal. For session-based I think that you can already decide if the session is null or not.
the validator only gets called if the session is non-null for the applicable type:
Copy code
val session = call.sessions.get<T>()
        val principal = session?.let { provider.validator(call, it) }
I have optional authn working ok with sessions as it is -- the problem is that the authn code doesn't get called at all if there is no session.
To rephrase, I'd like to do something like set
X-authn-state = true
if you have a cookie that maps to a valid session that maps to a valid user, and
X-authn-state = false
in all other cases
for context, optional stuff works fine with
like so:
Copy code
session<ApiSessionData>("name of optional auth") {
    challenge = SessionAuthChallenge.Ignore
I would open an issue for that