I am currently working on the logic of custom token validation. I need to deactivate the token when the user's password is changed (change-password endpoint is public).
I have implemented the ICustomTokenRequestValidator interface and resolved my class via DI
.AddCustomTokenRequestValidator<TokenHashValidatorService>();
However, I can see the following problem, my implementation of ICustomTokenRequestValidator only works when I generate a token and during only the first request to my API.
In logs I see the following information:
JWKS request from log
During first request to API request to /.well-known/openid-configuration and /.well-known/openid-configuration/jwks is sent. But when I send a second, third, etc. requests my breakpoint in TokenHashValidatorService is skipped.
Is there any way I can forcefully initiate second /.well-known/openid-configuration and /.well-known/openid-configuration/jwks requests?
Or maybe I can somehow mark that "token validation needed" during the change-password flow?
I'm really stuck and out of options, I've read all the articles out there, any ideas?
Related
I hope this perhaps isn't too generic of a question. In gatewayAPI based microservices architecture pattern in .net - is it possible for a method dressed with [AllowAnnonymous] to call a method from another microservice that is dressed with [Authorize]?
The challenge that I have is that I have a payment processing method, which posts to another microservice to send an email confirmation, but the email method is marked authorized, and payment one is not.
Yes.
Think of it in terms of who is making the request.
A user makes a request to your endpoint, if there's any authorization, it's processed against the user's session token, form data, other cookies, etc that were included in the request by the user's browser.
If your code spins up an HttpClient and sends a request, the 'user' in this case is your server. If authorization is required, you'll need to include that in the HttpRequestMessage. What that looks like exactly depends on the endpoint you're hitting.
I’m writing a web api that will be called from a background service to fetch some data. After some research I decided to use a Json web token to achieve that but I’m still a bit confused regarding when a new token should be requested.
Let’s say I start up my service, I request a token, the token expires after 15 minutes, then after 20 minutes I make an api call with the expired token. I will get an unauthorized error or something.
My question is: How will the client know when to request a new token? Should it request a new one before every api call? Seems like I’m missing something. Maybe I should make the token permanent and store it in the database?
Thanks
The answer to this is slightly application specific, but the OAuth specification has a mechanism for "refresh tokens", which can be used to grant new "access tokens" (the token typically included on each API request), without having to send the user to the UI authentication process to have them re-authenticate. So, once you request an access token, you will receive a refresh token and an access token. This methodology allows access tokens to be used for much shorter time frames.
This can also be done without refresh tokens, but in those cases the access token timeout would likely be longer, and then you would request that the user re-authenticate through the usual OAuth UI process. Note that even when you do have refresh tokens, the refresh token can also be set to expire, in which would then require a user re-authentication through UI again.
In some API's you just make the API request as usual, and if you get a response that is defined by the API to be one that indicates the access token has expired, you can then issue an API call to refresh the token (or fully request a new one if that is expired, or you the API doesn't have refresh tokens), and then make the original API call again with the new access token.
The API can also have a response that includes the timeout or expiration date/time of the access token as well. Then, the client can avoid sending the initial API call first, and simply send the refresh token call first.
In implementing your API, you could likely use any of these methodologies.
Here's some general discussion on the OAuth spec website, to provide more depth:
https://www.oauth.com/oauth2-servers/making-authenticated-requests/
https://www.oauth.com/oauth2-servers/access-tokens/access-token-lifetime/
https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/
And also, here's an example from the Twitter API regarding response codes showing one of the access token expiration techniques (see the "Error Codes" section, under error code 89, which implies the token has expired and you need to get a new one):
https://developer.twitter.com/en/docs/basics/response-codes
Since your client is background service , you can use the Oauth2 Client Credential Flow . Your background service can request an access token using only its client credentials when the client is requesting access to the protected resources under its control.
With this flow , you does't need to care much about the token expires , if client sends an expired token to web api , web api validate the token and create token expires response to your service , your service check the status code/response , directly send a new token request to web api to get new access token , there is no need to use refresh token which uses in other flows .
The fact is that your harness should be prepared to request any token when getting an Unauthorized status code. What I do in test is to check the expiration datetime, if close enough I refresh or get a new token whatever applies to your Auth. Also when getting an unauthorized status code my code does a refresh once and keep a count. If I get another unauthorized code then I return a false or throw an exception after I log the error on the second try. This works fine for me.
I've got all the code working to generate the JWT and I've wired up my ConfigureServices with the proper config code but I'm not seeing the header actually get set.
I assumed that the middleware would do this for you but maybe not, is it up to me to return the token from the login method of my controller and the client to then take it and set the header for subsequent requests?
No it does not.
The way it works is that you send your login credentials to a login server. In most cases its the same but in more secure applications this won't be the case.
The server then authenticates your credentials, creates a JWT token and sends that back to you.
You can then use that JWT in your header when making a request to the application server:
"Authorization":"Bearer xxxxx.yyyyy.zzzzz"
This needs to be done with every call to the server because the point of JWT is that it is stateless, meaning the server does not save the data at all. Instead in reads the JWT token with every call and grants access/functionality based on that.
I have created a webhook custom sender project as described in here. When I try to subscribe to the webhook using postman I get a login error. As per my understanding to subscribe, I must provide a dashboard sort of thing where users come and subscribe to events. I want the user to call the subscription API directly from there own app. how I can do that? I don't see any documentation which tells me about all the parameters in the subscription request. need help.
You get the login error because you probably decorated the controller with Authorize attribute and you need to be logged in in order to access the actions within. You can replace AllowAnonymous attribute if you don't need to be logged in.
If you do, then login normally on the site and grab that cookie(token, etc.) which holds the authentication information and send that along with the Postman request.
I have a ServiceHost that implements many Contacts on various endpoints and bindings ((http & https) x (rest & soap) with Anonymous Access, Windows, or Custom authentication, as bound depending on the Contract) & nettcp with Windows authentication. Custom authentication is embedded in the http or soap headers. Each endpoint and contract has its purpose. It should all be manageable on a single ServiceHost - I don't want to split it up.
I've gotten it to the point where all the endpoints work and serve their content correctly, but the authentication/authorization isn't integrated into the WCF stack. I have been using a MessageInspector to handle validation of the authentication header and allowing it if the token was valid.
Now I want to integrate the authentication/authorization into the WCF stack. I want to be able to access the identity and check the claims in each Operation's implementation. And perhaps basic claims can be authorized centrally, like "are these claims authorizing anything at all in this contract?" (by contract type).
In the case of custom authentication, I have a signed/secure token that includes a custom implementation of identity and property claims which I can properly extract and convert into WCF claims upon receipt (even if I don't know exactly where to put them once I've got them). For Windows authentication, I just need access to the default Windows identity stuff.
I can set the ServiceAuthenticationManager and ServiceAuthorizationManager each to custom values, but it's not doing anything I want it to and I'm getting totally lost.
For example, the ReadOnlyCollection<IAuthorizationPolicy> authPolicy coming into Authenticate() seems to be inconsistent - sometimes it's empty, sometimes it has one UnconditionalPolicy and sometimes it has 2 or more (4?) of my custom IAuthorizationPolicy already there. Meanwhile IAuthorizationPolicy.Evaluate() gets executed anywhere from 0 to ~9 times per request. Sometimes, within IAuthorizationPolicy.Evaluate(), OperationContext.Current is null! And sometimes the evaluationContext.ClaimSets already has my claimset. Yet state is always null even when I give it a value in a previous enactment.
Rather than tackling these problems individually, I think it'd be better to step back and ask for some high-level explanation of what I should do/expect to see.
Authentication: When a request comes into the ServiceHost, it needs to get Authenticated. At this point in the pipeline, I don't need to know what they can do, just who they are. If a client submits both Windows credentials and a custom authentication ticket to a Contract/Binding on which I require just a custom authentication ticket, the service shouldn't be tricked into evaluating the wrong one. But perhaps at this stage in the WCF pipeline, the Contract hasn't been resolved so perhaps during this stage, all found identities/claims/tokens should be captured and selected among later. Is this right? How is this done?
Message Inspection: I have a custom MessageInspector which I'll still need for CORS support and OPTIONS request processing on some of the endpoints. I believe this happens after authentication and before authorization. In the case of OPTIONS, I set ref message to null and skip the Operation entirely, jumping straight to the BeforeSendReply. Clients don't send the auth-token on a CORS OPTIONS preflight request and so I allow these requests unconditionally.
Authorization: Depending on the Contract, I want to require certain authentication mechanisms and ignore others. I believe some setup needs to prepare the Thread Principal and Operation Context principal to the correct value. It seems that multiple Authorization policies can be in play at once. How do they interact?
Operation: I want to be able to implement each operation assuming that the identity of the caller is authenticated using a supported authentication (by Contract, which I'm OK maintaining hard-coded somewhere ONCE) and get the validated caller identity and assert simple permissions checks againsts the verified Claims.
How do I achieve this (code preferred over config xml)?
Thanks!