Always receive 401 when accessing api with a valid token - asp.net-core

Starting with the following repo at https://github.com/mjrousos/IdentityServer4Authentication, I added a "ValuesController" with a single "Get" method with the [Authorize] attribute. When I login using the web front end I'm able to access this endpoint just fine - the web bits contain the standard web bits found in the IS4 Quickstarts.
However, when I request a token from the token endpoint (/connect/token) with the following body (raw) "grant_type=password&username=gvdonovan%40gmail.com&password=Pass20!7&client_id=myClient&scope=myAPIs" and then use this token in a Get request with a single Authorization header with a value of "bearer [my token]" I receive a 401 Unauthorized response.

You've got your Identity Server and your 'protected controllers' in the same project, with a single startup, which is a configuration I'm not used to.
For our use of IdSvr, we made sure that the startup for the client (a web api) used the middleware "UseIdentityServerAuthentication" in the configure method, with appropriate definitions for what the acceptable Authority and AllowedScopes are for that client.
Then the use of the Authorize header on protected API resources will auto-magically call the authority (our IdSvr) to verify the token.
Our IdSvr doesn't have controllers or "app.UseMvc", because it is just for issuing/verifying tokens.

Related

Getting refresh_token server-side (sessionToken) with Okta

We wish to use our own httponly strict cookie with access and refresh token in it for our microservices architectures.
We are primary using OKTA Authentication API to log users with our own custom Sign-in page.
We were able to get the access_token on the authorize endpoint using the responsetype=token with sessionToken and redirecting the result as a form_post on our back-end endpoint.
I was unable to retrieve the refresh_token despite adding the offline_access in the scope even if it is checked in my okta application setting.
I don’t want to use resource password flow since we prefer using sessionToken which will work with multi factor if needed in the future.
I also try using the code flow and redirecting the result on our back-end but since the code flow is client-side it’s return this error "PKCE code verifier is required when the token endpoint authentication method is ‘NONE’." This error occur even if we choose a .NET application
How can we retrieve the refresh_token server-side with Okta?
Responded to your post here https://devforum.okta.com/t/getting-refresh-token-server-side-sessiontoken/12419/3.
Aside from making a call directly to /token with your access token you can also check our Early Access feature called Refresh Token Rotation. Let us know if this helps!
I was able to use the CODE flow and redirect from server-side to the authorized endpoint like so:
https://{YOUROKTADOMAIN}/oauth2/default/v1/authorize?client_id={YOURCLIENTID}&response_type=code&scope=openid%20offline_access&response_mode=query&redirect_uri={YOURSERVERSIDEGETURI}&state={Guid.NewGuid()}&sessionToken={SessionToken From Auth API}
This call will post back to my same server, so i can handle token myself and create my own cookie.

JWT handling with WSO2-AM

we plan to introduce an API management solution and we're currently setting up a proof of concept with WSO2 AM. We want to use the WSO2 API gateway to check whether a certain consumer application is allowed to use an API and to throttle the request rate.
I work on the identity workflow and I wonder how a consuming application can pass a JWT token to the backend service with WSO2-AM in between.
First, this is our current scenario:
Without API gateway
The consuming application gets a JWT token for its carbon user from an identity provider. The JWT contains some claims about the user, e.g. the roles he/she belongs to.
The app calls the service an passes the JWT token in the Authorization HTTP header like: Authorization: Bearer
The service validates the issuer and signature of the JWT and retrieves the claims from it.
So, this is pretty straight forward. Now we put an API gateway in between the application and the service:
With API gateway
The consuming application gets a JWT token for its carbon user from an identity provider.
The consuming application uses OAuth2 to get an access token for the following API calls. We can use the client_credentials grant type and simply pass the the client id and client secret. I haven't yet tried it, but we could possibly use the JWT grant type (see https://docs.wso2.com/display/ISCONNECTORS/Configuring+JWT+Grant+Type) and use the JWT for passing user information to the API gateway.
The API gateway validates the JWT against the public key of the identity provider when using the JWT grant type.
An access token is returned to the app.
The app sends an API request to the gateway and passes the access token in the Authorization HTTP header.
The gateway validates the access token.
The gateway forwards the API request to the service.
And there is my problem: How can the JWT from 1/2. be passed to the service?
There is a documentation for "Passing Enduser Attributes to the Backend Using JWT" (see https://docs.wso2.com/display/AM210/Passing+Enduser+Attributes+to+the+Backend+Using+JWT), but this would introduce a new JWT, issued and signed by WSO2-AM, and I'm not sure, whether this JWT contains all information from the JWT used to create the access token (or even the original JWT).
Another way I could think of is using a custom HTTP header for passing the JWT through the gateway to the service. I cannot use the Authorization header (as we do without the API gateway), because WSO2-AM expects the access token in that header.
Since I'm not happy with either solutions, I want to ask the experts: How would you solve this?
Thanks,
Torsten
The only possibility I can think of is to send the JWT token in a custom Header for the backend service.

JAX-RS Jersey servlet JJWT

I have a couple of days following a few issues but I can not find the solution .
I have followed these issues: Custom JAX-RS authorization - using JWT in each request and
Best practice for REST token-based authentication with JAX-RS and Jersey
but I do not understand how to use filters.
I need to create a token for a android app Use the resources of my web service.
I can not just create a token and send it ?
I 'm using jjwt https://github.com/jwtk/jjwt but I think it right, a piece of code:
#POST
#Produces("application/json")
#Consumes("application/x-www-form-urlencoded")
public Response authenticateUser(#FormParam("username") String username,
#FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
// authenticate(username, password);
// Issue a token for the user
String compactJws = Jwts.builder().setSubject(username).signWith(SignatureAlgorithm.HS512, "pepe").compact();
// Return the token on the response
return Response.ok(compactJws).build();
} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
If anyone can help me , thanks ...
Si alguno me puede responder en castellano, mejor.
PD: Sorry if I asked the question wrong, I'm new in stackover... and sorry for my English
I am the author of the answer about token-based authentication in JAX-RS. This authentication method can be summarized in the following steps:
Exchanging hard credentials for a token
No filters are required to do it. You should have an endpoint (a JAX-RS resource method) to perform the authentication using hard credentials (like username and password). If the credentials are valid, the endpoint is going to issue a token that will be sent to the client in the response payload. The client must sent this token in the Authorization header of each request.
The endpoint that issues the tokens must not be protected, that is, no authentication must the required to access it. Once you have an Android application as client, I think you will find better consuming application/json instead of application/x-www-form-urlencoded. My answer provides details on how to do it.
Validating the token
Here the authentication filter comes into play. When using filters to validate the tokens, you can keep your endpoints lean and business focused.
The idea behind the filter is to intercept the requests to protected resources, extract the token from the Authorization header and validate it. If the token is valid, the request will proceed to the requested endpoint. If the token is invalid, the request will be aborted.
Besides the authentication filter, you can have other filters to perform authorization, for example. In the authentication filter, you must check if the token is valid and then find the user you issued the token for. In the authorization filter, you must ensure the user has enough permissions to access the requested resource. Other filters can be created according to your needs.
The code you have provided is valid to a issue a new token for a web application (uses application/x-www-form-urlencoded), but for android application It would probably be more appropriate send credentials as a json POST or in a Authorization header
After this, the client application receives the token, stores it and needs to include the JWT in every request to server. You can include the token in headers or in a request param. The server must validate the token signature, and other fields like sub (the userId) and exp (expiration time).
Using a filter, like the AuthenticationFilter provided in the example, simplifies the authentication process. It can intercept all the requests and perform the validation in a unique point. If not, you would have to validate the JWT in each method of your bussiness logic
If you have doubts about how to configure the filters I suggest to post in SO an specific question

Using bearer authorization with PostMan

I am looking for an easy way to add bearer tokens to PostMan. I have imported my API into PostMan from a swagger definition, and am wondering if authorization can be added automatically to all requests in some easy way, such that I do not have to change the Authorization header for each endpoint whenever the token changes.
I am currently requesting a token at /token for my API by sending an x-www-form-urlencoded request containing the parameters username, password and grant_type with a password value.
The returned access_token is then appended to the Authorization header in the format "Bearer token-received-from-token-endpoint" for each request to the API.
The backend is implemented with AspNet Identity Framework and AspNet Web API 2.
Good approach here is chaining request
When you get a token, assign it to an environment variable and use that variable in your subsequent requests.
This way you will have a fresh token every time and your other requests can use that on runtime

Open Auth Authentication in ASP .NET Web Api

I am writing a ASP .NET WEB API Application which can be accessed by other devices and applications to interact with my Application hosted in IIS. How can I give OpenAuth Authentication for the WEB API Application. Am using MVC 4 in VS 2010 and hence my framework is 4.0. Please give me some suggestions.
You can authenticate a web API using Individual Accounts. Protected recource will contains the Www-Authenticate header with value "Bearer", indicating that the client must authenticate using a bearer token.
A bearer token is a particular type of access token. An access token is a credential string that authorizes a client to access a protected resource. (See RFC 6749.) A bearer token is an access token that can be used by any client. In other words, a client can use the token without proving that the token was issued to that particular client. (See RFC 6750.) For this reason, bearer tokens must be used with SSL. If you transmit a bearer token as plaintext, anyone can intercept it and get access to the protected resource.
All info about that can be found HERE