last day (16 days later) » 

12:32 PM
1
A: Disable Bearer Token validation for a controller method

TsengUsually you decorate controllers or actions which you want to allow w/o authentication with [AllowAnonymous] (see docs). If you have multiple authentications (Jwt, Cookie) and you want specific endpoints only allowed with a specific authentication, you use the scheme attribute, i.e. [Authorize(S...

 
I've tried AllowAnonymous but it does't work.
 
Cause you are still sending the token I assume. Don't send a token (from the client) on actions which doesn't require authentication
 
I cannot control the client unfortunately. They may send it anyway. Is there a way do disable it regardless the client sending the token?
 
The code you got above is about token validation (expiry date, audience, issuer, signature), not authentication. So its the wrong place to check. When a client sends a token, the rest service must assume that the user want to access an protected action. When no token is sent, no jwt validation will should be performed and it drops back to the authentication middleware.
Anyways, not even sure why you check on OnTokenValidated, this call back is called after the Jwt token has been validated and the claim principal was created (means: the user has been logged in/authenticated successfully at this point). When its called, you already know the token is valid. What is your goal in performing checks there? Token revokation?
 
I check if the token is still valid (expired etc) if it has expired it will return invalid token. There are clients that may call the api every 5 min a method that doesn't requires a token (public). When the token expires those client will get 401 because the token validation will trigger
 
12:32 PM
The documentation says: Invoked after the security token has passed validation and a ClaimsIdentity has been generated. This means that expiry, issuer and audience is ALREADY valid when its called, so why checking it a second time?! When ClaimsIdentity is called, it means that all checks been valid and the user is authenticated
 
this is where I check if the token store on the DB is the same as in the request + expiring date
 
You don't have to do that, a JWT is self-contained. Its protected by its signature. The whole point of JWT is that you don't need round trips to the database and by just validating its content and signature is enough to know its valid. What you are doing is opposing to what JWT is meant for
 
what if I want to reset the client token to make it invalid ?
 
That's called token revocation, which is what I asked and you didn't replied. This can be handled differently (putting a unique value and using local (or distributed) memory cache and validate it there, on revocation just remove the key). But this is actually a non-issue. access tokens (if thats what it is) are meant to be short lived (depending your security urge, 5 to 60 minutes) and then need to be refreshed
With a short lived access token, revocation is a non-issue essentially. Otherwise (IdentityServer 4 approach), you use opaque tokens instead, it does similar approach but you dont send JWT with each request but a jwt token and the webapi fetches the claims and refresh the token on the backend
 
in my app I have a session manager class
 
12:34 PM
And if its just an identity token, then it matters even less, since the identity token only validates your identity, not authorization (which manages permissions)
 
basically when a client authenticate usgin gogole or facebook I gnerate a token and store it on the db
at each request I chekc if the token is valid
token is valid for 6 months
after that user has to re-login
 
Thats not how or what for JWT was designed. If its access token it should be short lived, if its an identity token it can be long lived
 
basically session manager swap the google tocken with a jwt created on the backend
 
Its important to know the difference. Identity token only confirms your identity. The access token grants you permission to the resources (i.e. to Google or Facebook API)
 
if (user == null)
{
throw new ArgumentException("Arguments to create token are not valid.");
}

var securityTokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(this.GetClaims(user)),
Expires = DateTime.UtcNow.AddMinutes(authOptions.Value.TokenExpiration.Value),
SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256Signature)
};

var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
 
12:37 PM
Then you need a refresh + access token. The access token is used for accessing the resources and expires soon (5 to 15 minutes are common) and refresh token is used to obtain a new access token. When the refresh token is used you validate if its been revoked or not, but not on the JWT
 
this is the core method where I validate if the google token is valid after that I create one and store it on the db. Then I return it to the client
basically this was to avoid that
we got this token valid for 6 months
that's why we store it on the db
of course doesn't call the db all the time becase the token is cached
now for some methods we want to skip that but because the client still provide the token
the onvalidation event triggers
 
Still got the feeling there is confusion between identity, access and refreshing tokens I think
Yea, but you method doesn't failed because a client provides a token
It fails because the token is invalid, which is the correct way imho. If the token is valid, it would continue down the middleware and call the action and [AllowAnnonymus] should then work
 
yes unfortunately that's we what we got :-(
 
It fails only when token is provided AND token is invalid
 
*what
yes exaclty. The idea would be check if the mothod has anonyous and skip it
sorry meeting
 
12:41 PM
Having no token should have it pass, as well as having a valid token
But its wrong from process point of view
A valid token should always be refused, even if the called method doesn't need it or the token not be provided in the first place. Its wrong usage to pass an invalid token to an api which doesn't even require one. Imho it sounds more like you have two separate apis which should be treated as that (with two different openapi definitions and two separately generated clients on the caller side)
While Anton's answer may solve our immediate issue, its still kinda "wrong" in the bigger sense. You can call it flaw in the design itself
Because, even with Antons answer you will get the same issue when the token expires, because then the middleware won't call OnTokenValidated at all and just refuse it
 
ok so how can I call a method that dosn't required a token
even if the client is passing it
I would like to add an attribute on the method that make it skip the ontokenvalidated
if it is possible
 
Well one way is to filter out the Authroization Header early on in a middleware
for actions/controllers which don't need it. Its tricky thing to do with ASP.NET Core 2.x though since the old routing middleware doesnte valuate routes early enough in the pipeline (just when UseMvc is called but then its too late usually)
ASP.NET Core 3.x should by now have the new Endpoint Routing middleware allowing evaluation of routes early on. Didnt worked with it yet though. ASP.NET Core 2.2 has it to,but just internally (in preparation of 3.x), so not sure you can access it soon enough there in the older versions
 
1:23 PM
thanks a lot for your help
 
1:43 PM
But still, I don't see any issues the Jwt middleware returning 401 when the token is invalid. Any client should be able to handle this case, and ask the user to (re)login on revoked (or expired) token, then repeat the request (now with a valid token) and be able to access the api endpoint
Any well behaving Rest client has to do that anyways and its not you task to fix stuff of non-well behaving clients
 

last day (16 days later) »