Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add basic auth #13

Merged
merged 2 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,13 @@ Each JSON configuration file for the gateways can specify detailed settings for
]
}
```

## Authentication
Basic authentication can be enabled using the `--basic-auth` flag. The username and password should be set through environment variables `GATEWAY_USERNAME` and `GATEWAY_PASSWORD`, respectively.

### Running the Application
To run the application with authentication:

```
DEBUG=true GATEWAY_USERNAME=myuser GATEWAY_PASSWORD=mypass go run . --config config.json --basic-auth
```
17 changes: 17 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ func main() {
Usage: "Load configuration from environment variable named GATEWAY_CONFIG.",
Value: false,
},
&cli.BoolFlag{
Name: "basic-auth",
Usage: "Enable basic authentication.",
Value: false,
},
},
Action: func(cc *cli.Context) error {
configPath := resolveConfigPath(cc.String("config"), cc.Bool("env"))
Expand All @@ -73,6 +78,18 @@ func main() {
r.Use(httplog.RequestLogger(logger))
r.Use(middleware.Recoverer)
r.Use(middleware.Heartbeat("/health"))
// Add basic auth middleware
if cc.Bool("basic-auth") {
username := os.Getenv("GATEWAY_USERNAME")
password := os.Getenv("GATEWAY_PASSWORD")
if username == "" || password == "" {
return errors.New("both GATEWAY_USERNAME and GATEWAY_PASSWORD environment variables must be set for basic authentication")
}
r.Use(middleware.BasicAuth("API Realm", map[string]string{
username: password,
}))
}

server := &http.Server{
Addr: fmt.Sprintf(":%d", config.Port),
Handler: r,
Expand Down
Loading