How I try to automate a repetitive task of extracting a token from a string
Tags: python, automation, programming
Published: 2022-01-14 13:19:59

## Use case

I'm using [Swagger](https://swagger.io/) to load mock values into a system.

To do that, I need to [authenticate using a bearer token](https://swagger.io/docs/specification/authentication/bearer-authentication/) from another system that also uses swagger.

I also need to do at least one request to get the curl request that contains the token.

Once done, I copy and paste it on a notepad before choosing only the string after the bearer token. Here's an example:

Source:

```
curl -X POST "http-some-api" -H "accept: */*" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
```

Target:

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```

I do this several times throughout the day when working on this project.

Here's the project [GitHub repo](https://github.com/abdallahYashir/extract_token/tree/develop).

If you want more information:

> - what is a bearer token? The bearer token is **a cryptic string, usually generated by the server in response to a login request**. The client must send this token in the Authorization header when making requests to protected resources: Authorization: Bearer <token> [1]
> - how to generate one? [2]

## Automate

I begin thinking on how can I spend 30 mins to 1 hour automating at least getting the exact token I need.

My use case is that once I copy the curl string, I just click on the script, and it adds the token in the clipboard.

I then just need to paste it into the swagger target auth input.

## Technology

As usual I'm using Python which I think it's one of the best programming languages for automating scripts.

I use the pyperclip package to read from and write to the clipboard.

Then pyinstaller to generate the exe file.

I also use pipreqs to manage dependencies.

I've also copied pasted the gitignore from:

https://github.com/github/gitignore/blob/main/Python.gitignore

## Project

I use PyCharm community edition to create the project.

I empty the default main.py file.

I break down each function to do only one thing.

```python
import pyperclip


def copy_from_clipboard():
    return pyperclip.waitForPaste()
    # return pyperclip.waitForNewPaste()


def copy_to_clipboard(content):
    pyperclip.copy(content)


def extract_bearer_token(content):
    # check if the string is present otherwise do nothing
    if "Authorization: Bearer " in content:
        # ignore the header parts and only take the token
        header, token = content.split("Authorization: Bearer ")
        # strip any leading and trailing whitespace
        return token[0:len(token) - 1].strip()
    return None


if __name__ == '__main__':
    content = copy_from_clipboard()
    token = extract_bearer_token(content)
    copy_to_clipboard(token)

```

Moreover, I still can separate the detection of the bearer token and extracting the specific string.

This is recommended as it's easier to unit test.

## Improvements

In terms of User Experience (UX), I also need to manually click on the exe file each time I want to get the token.

A simple improvement is just launching the script once and it will automatically listen to any clipboard event.

From that it will detect and extract as appropriate.

## Conclusion

I believe automating tasks, especially the repetitive and boring ones, can help free our time in the long run, so that we can learn new things and help more people.

You can ask me any question on [Twitter](https://twitter.com/AbdallahRamsing).

## References

[1] - https://swagger.io/docs/specification/authentication/bearer-authentication/#:~:text=The%20bearer%20token%20is%20a,Authorization%3A%20Bearer

[2] - https://jwt.io/

## Highly Recommended Resources

1. https://automatetheboringstuff.com/
2. https://gto76.github.io/python-cheatsheet
3. https://github.com/vinta/awesome-python