Gin framework should not accept request from any other tool

I have rest api which is written in gin framework.

I would like to restrict. It should work only from application not from tool like postman on production

What do you mean? If you want to restrict connections to localhost you can do something along the lines of this:

// Listen on localhost
err := http.ListenAndServe("127.0.0.1:8080", nil)
1 Like

Api should work from angular application only . not from postman or any other http client .

hi,
first thing, I’d like to understand “why” you have this requirement.

But in general you can’t limit who uses your API; in theory you could put some info in some special header (or cookie), but no one forbids who is using Postman to set the same header.

The question about “why” is because we need to understand the reasons and maybe provide alternative solutions

1 Like

As Dean_Davidson already pointed out, is restricting access via either localhost or internal IP, the only way I have found.

In my case I have 3 VPS. One for the app, one for the API and finally one for the database. API and Database is locked (“safe boxed”) for connection for direct internet communication. All communication to the API is done from the web app by either localhost or internal IP.

This is a physical solution that is guarded by VPS firewalls and hence unreachable from internet the normal way.

It sounds like you might want to implement some form of authentication for your api, and have your client application authenticate before making api requests.

1 Like

Yep. It sounds like you need to back up a bit and learn about authentication. Maybe start here?

Or here:

But the important bits are: you can’t restrict access to your API without a private key of some kind (which is how, for example, you authenticate with APIs like Stripe; because you keep a secret key in a secure environment you control). And you can’t bundle a private key with your client app (an environment you don’t control). So you need a public-facing way for clients to authenticate themselves.

1 Like

As people said above me, you should implement auth on your routes. For example here

r := gin.Default();

r.POST("/create-something", auth.VerifyJWT, packageCreate.CreateSomething)

VerifyJWT is my custom function for checking JWT tokens.
As you can see here how I did it, I’m first verifying if user is logged in (I’m using JWT tokens inside cookies). So it first checks if token is valid (is user is logged in). If it is, it will proceed to "package.Create…) to fire the desired function.

If it fails on VerifyJWT, it will not let user to create the post. Even if someone gets your API and tries to for example create post via postman (not logged in), it will give him error which will say “user not logged in”

I think this is what you were looking for.

1 Like