How to test a REST service that uses JWT in SoapUI? - rest

I'm implementing some REST services. All my tests are made using SoapUI.
Recently I decided to adopt JSON Web Token (JWT) for authentication but I could not find any support for this on SoapUI (native install or plugins, nothing).
I found some online generators like http://jwtbuilder.jamiekurtz.com/ but fill all fields, copy/paste on SoapUI again and again for every testcase is not productive at all.
I'm wondering if there is a way to test JWT stuff in SoapUI or if maybe I need another tool. Any advice?
Thanks!

I've found a semi-automatic way to keep a valid JWT token across TestCases without losing too much time, using an external file containing the token.
Have an external tool generating a valid JWT token into a file.
Open your project in SoapUI and add a jwt variable with the value
${=new File('/path/to/token_file.txt').text}
In your requests, reference your variable as a JWT header with the value
${#Project#jwt}
When the token expire, just relaunch the generator script, and SoapUI will automatically load the new token.

SoapUI will call your authentication server and fetch the token, then it will automatically put that token into authorization header (Bearer <token>).
Add new authorization>OAuth 2>Resource owner password credential grant
Then add your username and password into both client and resource section. Finally , put your token end-point as access token url and save the authorization profile to use in other test cases.

Related

.NET 5 Web API Jwt Token from external issuer

Im trying to make an .NET 5 Web Api works with Jwt Bearer token. I want some operations to be secured by using a token that comes from another issuer. The token would be generated by MS Azure AD. The application will read the token from the request header, validate it and extract the user's roles for more validations. The app shoudn't be the issuer of the token.
Is this possible? I tried so many ways to make this works without success. I setup Swagger to use OpenId Connect with Microsoft Azure and then the bearer is used to call the secured operations but always got errors. Now I don't understand how Dotnet Core Authencation and Authorization works.
Thanks in advance!
That will definitely work OK but requires an understanding of the science:
AZURE AD TOKENS
I would first look at the JWT in an online viewer. There is a known issue with the default setup where you get JWT access tokens that cannot be validated. See Step 3 of my blog post for details.
UNDERSTAND PRINCIPLES
Validating a JWT involves the general steps in this blog post. Once you understand this it will hopefully unblock you.
C# JWT ACCESS TOKEN VALIDATION IN APIs
The Microsoft framework often hides the required logic, which doesn't always help, and the option I prefer is to validate JWTs via a library.
Aim to understand how to use the JwtSecurityTokenHandler class to validate a JWT manually, eg in a console app. Maybe borrow some ideas from this C# code of mine.
C# AUTHORIZATION
Once JWT validation works, the next step is to use the details in the ClaimsPrincipal to determine whether to allow access to data. I would get on top of the JWT validation first though.

Decoding Keycloak JWT Token

I'm trying to validate (and read roles from) a JWT Token. Sadly I can't use any adapter or auto configuration due to my overall application architecture.
It's no problem to decode the token like any other JWT Token, but I wonder if there is a library from Keycloak to archive this goal. (For example Just Parse the token to something like a KeycloakJWTToken and verify it by grabbing the secret from Keycloak Server or so)
Any easy-to-use client or so?
I'm using the Jose4J library:
https://bitbucket.org/b_c/jose4j/wiki/Home
Reading the claims inside a JWT token is straightforward:
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
public void parseJWT(String token) throws Exception {
JwtConsumer consumer = new JwtConsumerBuilder()
.setSkipAllValidators()
.setDisableRequireSignature()
.setSkipSignatureVerification()
.build();
JwtClaims claims = consumer.processToClaims(token);
System.out.println("* Parsed token: "+ claims.getRawJson() );
System.out.println("* Expiration date: " + new Date(claims.getExpirationTime().getValueInMillis()) );
}
More examples are available on GitHub:
https://github.com/pvliesdonk/jose4j/blob/master/src/test/java/org/jose4j/examples/ExamplesTest.java
Last remark: you do not need a key nor a secret to parse the JWT, but if needed, you can use the server (public) key to verify the token was signed by the keycloak server you are trusting.
The JWT website is listing all libraries for Token Signing/Verification:
https://jwt.io/#libraries-io
Keycloak access tokens are indeed JWT tokens. So, you can make full use of existing JWT libraries, including for validation as stated in the Keycloak official documentation:
If you need to manually validate access tokens issued by Keycloak you can invoke the Introspection Endpoint. The downside to this approach is that you have to make a network invocation to the Keycloak server. This can be slow and possibily overload the server if you have too many validation requests going on at the same time. Keycloak issued access tokens are JSON Web Tokens (JWT) digitally signed and encoded using JSON Web Signature (JWS). Because they are encoded in this way, this allows you to locally validate access tokens using the public key of the issuing realm. You can either hard code the realm’s public key in your validation code, or lookup and cache the public key using the certificate endpoint with the Key ID (KID) embedded within the JWS. Depending what language you code in, there are a multitude of third party libraries out there that can help you with JWS validation.
Besides, in Java EE, using the Keycloak Java adapter, the roles are typically mapped on the user Principal and i.e. allows isUserInRole(). That's one of the goals.
Also it is possible to cast the Principal from the SecurityContext as a KeycloakPrincipal, then obtain in turn a KeycloakSecurityContext from it. Using the KeycloakSecurityContext you have access to both ID and Access tokens (when applicable) and can read their properties, attributes and claims.
Note that it is also good practice, and simply useful, to use the Keycloak UI to "evaluate" your tokens. For instance, you can see the generated token in the Client Scopes tab (under Evaluate), as well as evaluate your policies and permissions in the Authorization tab of your Client(s) (under Evaluate).
Cf. https://www.keycloak.org/docs/latest/server_admin/#_client_scopes_evaluate
That's probably the best way to debug and test, while setting up your Client(s).
If you select a user in the Evaluate screen, the following example data is generated:
Generated Access Token (...)
Generated ID Token (...)
Generated User Info (...)
All examples are generated for the particular user and issued for the particular client, with the specified value of scope parameter. The examples include all of the claims and role mappings used.
Source: https://www.keycloak.org/docs/latest/server_admin/#generating-example-tokens-and-user-info

registering a rest API with OAuth

I have written a web application which makes REST API calls to a message broker. The message broker contains already written REST APIs to which can be used to get message broker data. The message broker is written in a way in which each REST API call sends the user name and password which is encoded with base64. I need to make a login to my web app and authenticate it with OAuth.Does anyone know how to do this? How to authenticate the REST APIs with OAuth?
Step 1: Add OAuth 2.0 to your web server. This is very standard with lots of libraries available. You did not specify the Identity Provider that you will use (Google, Facebook, Auth0, Okta, etc), but each vendor has documents and libraries for you to use in your desired language.
Step 2: Add an Authorization Header to your API calls. The standard method is to add the HTTP header Authorization: Bearer access_token when making an API call.
Step 3: Add OAuth token verification to your API. When your API receives a request, it extracts the Authorization header and verifies the Bearer token. How this is done depends on the Identity Provider. For example, some vendors provide a Signed JWT (which you verify with the vendors public certificate), others provide an opaque access token (which you verify by calling the vendor's token endpoint). Add internal caching of tokens so that you don't need to verify on every API call.
If you understand OAuth 2.0 the above steps are straightforward to implement. If you don't Oracle has a set of videos which are excellent for getting started understanding OAuth.
Oracle Cloud Primers
If your desired OAuth implementation does not require users logging in and is a server to server service that you control on both ends, then you can use just part of OAuth which is Signed JWT (JWS). You create a Json data structure with your desired content and sign it with a private key. This creates a token that you can use in the above steps. You would then validate the token using your public key. You can use self-generated keypairs generated by OpenSSL or similar products for your signing and verification.

Mobile app + REST API authentication

I want to build a REST API which will be used by both mobile app and also a website. I was wondering how would I go about implementing a simple login system for users?
For a simple website, after checking the username and password, one could set a SESSION variable and have the user "logged in".
Now, REST is stateless so I suspect that the above is not the way to go about. I thought that a possible solution would be to have the server generate and return an access token each time the user logs in, and the client will need to attach this access token to every subsequent request to access protected endpoints.
Is the above a viable solution or what is the industry standard for something like this?
(I found OAuth 2.0 to be overkill, but I could be wrong)
There are several token authentication schemes, but if you're looking for the industry standard, then JWT (JSON Web Token) is the way to go. Here's how the process usually goes:
Client sends his credentials (e.g. username and password) to the server.
The server verifies that the credentials are correct, generates a JWT and returns it to the client. Client saves the token in e.g. localStorage.
For each subsequent request, the client will attach the JWT as a part of the request (usually in the "Authorization" header).
Server will be able to decode the JWT and decide if the client should have access to the requested resource.
Now, some interesting features of JWT come from the fact that there is data encoded in it. Some of it everyone can decode, and some only the server can decode.
So, for example, you could encode the user's id and profile picture in the JWT so that the client can use the data from it, not having to do another request to the server to get his profile.
JWT has embedded info about expiration. The server can set the expiration time.
Another cool thing about JWTs is that they are invalid if changed. Imagine you stole someone's token, but it's expired. You try to change the expire information inside the token to some time in the future, and send it to the server. Server will deem that token invalid, because the contents doesn't match the signature attached, and a valid signature can only be generated by the server.

How to download a file secured with IdentityServer

I want to be able to download a file from an API call. For argument's sake, let's say it's an automagically generated PDF file.
I have two problems:
Anchor tags can't add Authorization headers to the request, only XHR can.
XHR requests cannot download files.
My solution is to write my API with an [AllowAnonymous] end point in it, which takes the access_token as a parameter. I then validate the access token by hand and return a 401 or stream the PDF.
Is there a better solution than this or, if this is the best solution, how do I validate the access_token within the API?
This approach is totally fine.
If you want to use middleware to validate the token - it depends which middleware you are using. The plain Microsoft JWT bearer middleware has some events you can implement to retrieve the token from a query string alternatively.
The identity server token validation middleware has a TokenRetriever property which also allows you to retrieve the tokens from multiple/alternative locations.