BasicAuth for APIs in GO

In this blog, we shall be looking at following concepts :-

  • Meaning of Authentication.

Question :- Whats the meaning of Authentication ?

Answer:- Authentication is the act of checking that the entity accessing your system is who they claim to be.

Question :- What are the various Authentication Schemes available ?

Answer:- There are many authentication schemes that you can use :-

  • The basic authentication scheme is geared toward user and password management.

Question:- Whats the recommended way to store passwords ?

Answer:- If we decide to store passwords, never do it in clear text. Salt and hash them. You can use services such as Auth0 and Okta to manage users and authentication for you. These services will do most of the heavy lifting, but you will still need to integrate with them.

Question:- Demonstrate an approach to do AuthN in case of HTTP Servers ?

Answer:- In HTTP servers, you can use middleware to do the authentication without mixing it in handler code. Let’s look at an example below :-

Step #1.) Following are the dependencies, which we need to import :-

Step #2.) Here we have an HTTP with two handlers :-

  • The healthHandler does not require authentication.

Step #3.) :- Now, we will write the middleware (functionName → “requireAuth()”), which is a function that gets an HTTP handler and returns an HTTP handler. This function is going to do following tasks :-

  • Get the token → Add one function called authToken() which is going to get the token from the authorization HTTP header.

Step #3.1) :- Here is the method to extract token from header :-

Step #3.2) :- Here is the method to extract user from token :-

Step #4.) Here is simple code for healthHandler, which doesn’t require authentication :-

Step #5.) Here is simple code for messageHandler which does require authentication :-

Note the important thing from above snapshot :- This handler is very well able to access this authenticated user directly from the context now, because we did set the user into the context in step #3, line #50 above.

Step #6.1) Now, let’s verify the authentication behaviour with NO creds being supplied :-

Step #6.2) Now, let’s verify the authentication behaviour with Right Set of creds being supplied :-

Here are the logs visible :-

That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.

References :-

--

--

Software Engineer for Big Data distributed systems

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store