Create endpoint in Swagger to validate JWT token - c#

I have an API developed in .NET 5.0 in which I implemented Swagger.
Right now I have a endpoint in which the user obtain a JWT Token with a user and password and this token is used to authorize into swagger like below:
Authorize
Everything works fine to this point.
But now I want to implement and endpoint in which the user has to introduce this token to authorize swagger in order to use the API.
It is possible have these two validation? I want the user authorize through the button if they use the website but if they use postman (or another API) have to use the authorize endpoint.
I have searched to try this implementation and I found IOperationFilter but I'm not sure if its what I need

I don't have a clear idea about this, but if I understand what you want to do correctly, you want to remove the security measures in requests made through the website.
While doing this, you can create a public token or define a guest or similar role and perform the transactions that occur on the website as if you are playing this guest role.
But finally, I must say that your request will cause a major security vulnerability. Also, keep in mind that every transaction performed on the website can be easily imitated by tools such as postman. This will completely override your other security measures.

Related

Authorization check in different microservices

I decided to try for the first time to implement a microservice architecture instead of a monolithic one and ran into an authorization problem.
In a monolithic architecture, I simply passed the token in the header when accessing the controller on which the [Authorize] attribute was hanging and checked it against the current single database. But in the microservice architecture, each microservice has its own database, how you can check the token when accessing other microservices, I have heard about the implementation of the check in API Gateway, but I think that, anyway, each microservice should have its own check, since, there should be no access to the api if the user is not authorized.
Should I use api gateway to make a request to the authorization microservice for verification?
How can I implement this?
I have a separate microservice for user authorization (registration, login, issue of tokens) which has a database of users with tokens.
That is, I need to make a request to this microservice using API Gateway?
One way -
You should try to do authentication/authorization at API Gateway level. Whenever any API call come to API Gateway that needs some permission then check the token. If the access/token is not present then return 401. On frontend, if you get 401 then do authentication at UI.
2nd Way -
UI pass token to API Gateway that will further send the token to other microservices.
It depends on, how grain level of permission do you need. If it is at very grain level, then go with 2nd else go with 1st.

Blazor JWT Authentication

I am trying to figure out correct way to implement JWT auth with Blazor (WASM).
After going through the docs a got an idea on how the built in components work but still the whole picture is not clear to me.
So in my scenario i have an API sever that will be used, the API server can issue JWT tokens and they can be used to authenticate against the endpoints where required.
So right now i am trying to figure out the correct role for each component.
For start we have AuthenticationStateProvider, as i understand this component has the responsibility of obtaining the JWT token either from server or if one stored locally, also it could handle token refresh when required?
Now since i will be using Typed HTTP Clients i will be using IHttpClientFactory, along with that i will have AuthorizationMessageHandler to attach tokens to desired HTTP Client instances.
Things fall apart for me when i am trying to deal with IAccessTokenProvider, as i understand the default implementation will be called once a HTTP Client is created and http request is about to be made.
What is not clear is how this IAccessTokenProvider will obtain the token.
So the question is whether i should create my own implementation of IAccessTokenProvider and if so how it should handle the tokens.
As i said i wont be using any built in authentication providers and will have my own JWT auth system instead.
Thanks.
The first three paragraphs are very clear and correct. This is how you should do that. I can post here some code snippet to demonstrate how it is done in practice...
Things fall apart for me when i am trying to deal with IAccessTokenProvider,
No wonder... The IAccessTokenProvider is not relevant here. The IAccessTokenProvider is a token provider used in the new JWT token authentication system for WebAssembly Blazor App. But if you want to implement the JWT authentication yourself, you must do that as you've described in the first three paragraphs... which I can summarize like this:
When a user makes a first access to a protected web api endpoint and he's not authenticated (or registered), he's redirected to the relevant pages, type his credentials, etc, which you pass to your Web Api end point dedicated to authenticate the user (register if necessary, etc.), after which the action method called produce the JWT token, and send it back to the WebAssembly Blazor App running on the browser. You should store the JWT Token (perhaps in the local store), and retrieve it whenever you perform HTTP calls (Adding the JWT Token to the headers of the request).
The above described process also involve the implementation of the AuthenticationStateProvider object, that is updated with the authentication state, and notifies subscribers, such as the CascadingAuthenticationState, that the authentication state has changed, at the end of which process other components and objects adapt themselves to the new situation... you know, re-rendering, etc.
So, you see, you've received a JWT Token from your Web Api, stored it a local store, read it, and use it. Reading the Jwt Token from your local store and parsing it, to great extent, is something that the IAccessTokenProvider does, but in the new authentication system, and as you do not use this system, the IAccessTokenProvider is not relevant.
What about automatic Token injection in headers of HTTP client, can i or should i still investigate custom AuthorizationMessageHandler or this component would not be usable without IAccessTokenProvider?
You may add your Jwt Token to each HTTP call as demonstrated below:
#code {
Customer[] customers;
protected override async Task OnInitializedAsync()
{
// Read the token from the local storage
var token = await TokenProvider.GetTokenAsync();
customers = await Http.GetFromJsonAsync<Customer[]>(
"api/customers",
new AuthenticationHeaderValue("Bearer", token));
}
}
which is perfectly fine. But of course you can create a custom DelegatingHandler modeled after the AuthorizationMessageHandler or still better the BaseAddressAuthorizationMessageHandler as you're going to use the IHttpClientFactory to provide your HttpClient service. Try first to attempt to use them without any modifications, and if it's not practical just emulate their functionality.
The last things that bothers me is the implementation of obtaining access token and storing it locally.The best approach i can think of so far is to have a global authentication service, this service will provide the functionality of obtaining the token, refreshing it, storing etc. Both IAccessTokenProvider and AuthenticationStateProvider will use it when token is requested plus will be notified whenever authentication state changes like user logs in or out.
Perfect... Note: The AuthenticationStateProvider should be notified of the change in the status of the Jwt Token. As for instance, when you get a new token from your Web Api endpoint, your code should add it to the local store, and then notify the CUSTOM AuthenticationStateProvider of the change. Your code also should notify the AuthenticationStateProvider in case you delete a Jwt Token, so that your user interface will reflect this changes, etc.
Good luck.
Hope this helps...

How to get a Bearer token from Auth0 to impersonate a test user in an integration test?

Context
I am trying to write some integration tests that verify correctness of my RESTful Web API service (.NET Core-based).
To make requests that mimic the user's browser requests I'd need to configure an HttpClient's headers to include Authorization: Bearer {test-user-1-bearer-token}.
Problem
My issue is that I can not find a way to programmatically retrieve the bearer token(s) for the test user(s) I created by hand.
What I tried
According to my research of the Auth0 Architecture Scenarios the only one that could work for me is called Server Application + API.
That scenario relies on retrieving an access token for the testing Application (not a bearer token for a user the code is trying to impersonate).
As far as I understand, this prevents me from having multiple test accounts, which I need to have to be able to test complex, multi-user interaction scenarios around my Web API.
Alternative approach
Instead of using a real production-ready Authentication middleware, I could use a custom middleware when running the service instance for testing.
An environment variable, for example, could drive the decision about which AuthN middleware to enable.
That custom middleware could rely on a non-JWT token source (e.g. custom HTTP Header) to bypass the Auth0 authentication. 🤔
It would be nice to be able to test with Auth0 playing its role, however.
Ugh
I suspect that my question is off-topic because I'm not providing code.
Hopefully, I at least get some answers or comments that give me a clue.
For integration tests you could check if your auth service supports Resource Owner Password Validation flow or Client Credentials flow - it would be easier to obtain access token.
If you still going to do it with Implicit flow - there's a similar question answered - https://devforum.okta.com/t/unit-testing-and-implicit-flow/1210/3. You would need to change from Okta auth service to yours.
P.s.
That scenario relies on retrieving an access token for the testing Application (not a bearer token for a user the code is trying to impersonate)
Bearer token is an access tokens. No matter who bears it, testing app or end user.

How to Authorize request from another WebApi project

There are 2 WebApi Projects on different servers. One of these servers (WebApi-A) has OAuth2 authentication workflow setup with Authorization Server and all.
The another WebApi project (WebApi-B) has an end point that I would like to Authenticate through [Authorize] attribute. I don't want have a new authorization server but to utilize (WebApi-A's) authentication process just to validate the token.
From what I understand if the machine-key is same across these server. We can essentially replicate the authentication process from WebApi-A in WebApi-B without having to call WebApi-A at all.
How do I achieve this?
You could, in theory, pass through the JWT token and if your OAuth setup uses the same client secret and data store it should just work. You would have to ensure that you add the JTW token when requesting and to use some distributed cache to verify.
I would rather ask whether or not you should rather create a gateway that can handle and authenticate the requests and delegate them to the separate APIs? This feels like an identity server (http://docs.identityserver.io/en/latest/topics/apis.html) would solve your problem. Anything you do other than moving the authentication from web api A would just be a stopgap.
Duplicating the setup could work but that will mean that you have to now maintain it in two places. So I agree that doing that is less than ideal.
This is a great article that may aid you:
https://www.scottbrady91.com/OAuth/Delegation-Patterns-for-OAuth-20
This will have a lengthy answer so I will just leave you this diagram showing multiple Resource Server, Client, and a separate Authorization Server
Taken from this article Single sign-on across multiple applications (part II) which I hope could get you started.
you can use your token when login in web api and then you add the token to the header "Authorization" with bearer "your token"

Using IdentityServer4 to protect my website and API

I have a website set up that is responsible for the rendering of information fetched from an API that I have built; both of which are in .NET Core 2.1.
I want the API to handle the authentication using Bearer tokens to ensure that users have the correct permissions to make the calls they're using. I also want to protect my server-server communications too, so that my website can make authenticated calls to the API, without users themselves being authenticated.
I have been following the tutorials for IdentityServer4 and I feel like it's something I should be using to achieve my desired workflow.
However, the tutorials all force the user to redirect to the IdentityServer application to log in. This doesn't feel seamless; I don't want my users being redirected to another domain for authentication; they shouldn't have to leave my site.
Is it possible to send the username and password to my API and have the API authenticate with IdentityServer without the user seeing what is happening behind the scenes?

Categories