Set Request Headers in Swagger-UI

For the last 2 days, I was facing a issue with setting Global Request headers to Springfox’s Swagger-UI (version 2.8.0) for a SpringBoot Application.

The issue was more related to the new Swagger version 2.8.0 and does not any issues in prior versions. In the below code, I am only presenting the cause and the solution. Assuming the developers have prior knowledge of Swagger and its implementation. More implementation details can be found at https://springfox.github.io/springfox/docs/current/#quick-start-guides

@Bean
    public Docket apiSwaggerDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .securitySchemes(newArrayList(apiKey()))
                .apiInfo(apiInfo());

    private ApiKey apiKey() {
        return new ApiKey("access_token", "access_token", "header");
    }

Let’s only concentrate on the apiKey() method. The new ApiKey(…) constructor has different argument signatures for different versions of springfox’s swagger.

/**
* http://springfox.github.io/springfox/javadoc/current/springfox/documentation/service/ApiKey.html
* Signature of the ApiKey constructor
* return new ApiKey(name, keyName, passAs);
* 
* name - is the name of the key
* keyName - is the value of the key name
* passAs - you can pass as header or query parameter
*/
// For version 2.6.0
return new ApiKey("Authorization", "Bearer", "header");

Output at swagger-ui
name: Authorization
in: header
value: Bearer

// For version 2.7.0 - This version has reverse the constructor Argument signature
return new ApiKey("Authorization", "Bearer", "header");

Output at swagger-ui
name: Authorization
in: header
value: Bearer

// For version 2.8.0
return new ApiKey("Authorization", "Bearer", "header");

Output at swagger-ui
There is no header displayed in this version of the swagger.

For my current use case, I had to step down the swagger version to 2.7.0.

Alternatively, if one intends to use version 2.8.0, we can have globalOperationParameters to put in use, with all API’s requesting for header

@Bean
    public Docket apiSwaggerDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .apiInfo(apiInfo())
                .globalOperationParameters(
                        newArrayList(new ParameterBuilder()
                                .name("access_token")
                                .description("Access Token")
                                .modelRef(new ModelRef("string"))
                                .parameterType("header")
                                .required(true)
                                .build()));
    }

The only drawback using globalOperationParameters, the header is not sticky. Meaning, the same header value is required for each and every API in Swagger, which is not great.

Thanks for reading my post 🙂

More Reading & Resources:

Advertisements

Cyber Security – Penetration Testing Checklist

Hello folks,

Below is the list of Penetration Testing checklist notes that were discussed in the OWASP meeting I attended yesterday.

1). Web Applications – Check if a web application is able to identify spam attacks on contact forms used in the website.

2). Proxy Servers – Check if the network traffic is monitored by proxy appliances. Proxy servers make it difficult for hackers to get internal details of the network.

3). Spam Email Filters – Verify if incoming and outgoing email traffic is filtered and unsolicited emails are blocked.

4). Firewalls – Make sure an entire network or computers are protected with a firewall.

5). Exploits – Try to exploit all servers, desktop systems, printers and network devices (Within scope).

6). Verification – Verify that all usernames and passwords are encrypted and transferred over secured connections like HTTPs.

7). Cookies – Verify information stored in website cookies. It should not be in readable format.

8). Vulnerabilities – Review previously found vulnerabilities to check if the fix is working.

9). Open Ports – Ensure there are no unnecessary open ports on a network.

10). Telephones – Check all telephone(VOIP) devices.

11). WiFi – Test Wifi network security.

12). HTTP Methods – Review HTPP methods. PUT and DELETE methods should not be enabled on web server.

13). Passwords – Password should be at least 8 character long containing at least one number and one special character.

14). Usernames – Usernames should not be like “admin” or “administrator”

15). Application Login Pages – Application logins pages should be locked upon few unsuccessful login attempts (Brute force attacks).

16). Error messages – Error messages should be generic and not mention specific error details like “Invalid username” or “Invalid Password”.

17). Special Characters – Verify if special characters, HTML tags and scripts are handled properly as an input value.

18). Internal System Details – Internal system details should not be revealed in any of the error or alert messages.

19). Custom Error Messages – Custom error messages should be displayed to the end users in case of web page crash.

20). Registry Entries – Review the use of registry entries. Sensitive Information should not be kept in registry.

21). Scanning Files – All files must be scanned before uploading to server.

22). Sensitive Data – Sensitive data should not be passed in URL’s while communicating with different internal modules of the web application.

23). No Hard-Coded usernames or passwords – There should not be any hard coded username of password in the system.

24). Input Fields – Check all input fields with long input strings – With and Without spaces.

25). Password Functionality – Ensure reset password functionality’s secure.

26). SQL Injection – Check application for Cross Site Scripting.

27). XSS – Check application for Cross Site Scripting.

28). Input Validations – Important input validations should be done at server side instead of Javascript checks at client side.

29). System Resources – Critical resources in the system should be available to authorized persons and services only.

30). Access Permissions – All access logs should be maintained with proper access permissions.

31). Ending Sessions – Check that user sessions end upon log off.

32). Directory Browsing – Verify that directory browsing is disabled on the server.

33). Up To Date Versions – Verify that all applications and database versions are up to date.

34). URL Manipulation – Review URL manipulation to make sure a web application is not showing any unwanted information.

35). Buffer Overflow – Check memory leak and buffer overflow.

36). Brute Force Attacks – Check if systems are safe from Bruce Force Attacks – use a trial and error method to find sensitive information like passwords.

37). DoS (Denial of Service) – Ensure the system or network is secured from DoS (Denial-of-service) attacks.

 

All credits to Rob Taylor

Hope you’ve liked it.

Jason Web Token (JWT)

What is a JWT?



It stands for JSON Web Token and it replaces the older cookie authentication and is now becoming the authentication standard.

  • Simpler & light weight.
  • Don’t have cookie authentication problems like setting Session states either in memory or database.
  • No database lookup to identify who the user is, as userId is embedded in the payload which is part of JWT’s.
  • No CORS issues as cookies are not being used.
  • Works with small and medium handheld devices (phones and iPads/tablets).

JasonWebToken


Life of a JWT

Every JWT has three parts. It begins with a header, in between is the payload, and at the end is the signature.

It all begins with the client trying to log in, where the HTTP request is send over with email and password to the backend, whether it’s for a login or just register. The backend will then validate the email and password and then 
it will encode the user ID and a few other things against the secret and something called a payload. Then our JWT, which is comprised of the header,
 payload, and signature, will be sent to the client. At this point, the client gets the JWT. It has no idea what’s inside. It doesn’t know what it is 
because it can’t decode it, only the server can, and so it just saves it inside its local storage and as long as it has that entry inside the local
 storage, it believes that it’s authenticated. Now let’s say the client restarts. The JWT is still in local storage because it’s persistent and because
 of that they’re still authenticated. No matter how many times the browser or client might restart, they’ll still be authenticated, unless,
 of course, the JWT expires.

JWT Payload Details:

JWTPayload


What if a client wants to request a restricted resource?



A restricted resource can only be accessed if you are authenticated. So to make that work, what we do is, 
we take our JWT from our local storage (on the front end web app) and embed it into an authentication header, which then gets passed back with any sort of request 
we make to our backend for our resource. That way our backend knows who we are from the payload since our user ID is in it and can authorize
us to have access to this resource.