-
Notifications
You must be signed in to change notification settings - Fork 1
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
Implemented Authentication Middelware #21
Merged
Merged
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
fe8ca44
implemented add token for queue store
aneeshsharma 823cefe
implemented create token route
aneeshsharma 42120c2
Fix code style issues with gofmt
lint-action 4ec0ec9
read tokens in the queue in readqueue
aneeshsharma 9f4467e
Merge branch 'add-token' of github.com:SimplQ/simplQ-golang into add-…
aneeshsharma a44aee0
Fix code style issues with gofmt
lint-action d477b23
implemented token number
aneeshsharma c7875b4
merged origin add-token
aneeshsharma 5299a8e
Fix code style issues with gofmt
lint-action 085b8bd
added read token route
aneeshsharma 310e9fb
Merge branch 'add-token' of github.com:SimplQ/simplQ-golang into add-…
aneeshsharma 16e8417
Fix code style issues with gofmt
lint-action 534fd6a
separated name length constants
aneeshsharma 36a4f77
Merge branch 'add-token' of github.com:SimplQ/simplQ-golang into add-…
aneeshsharma 4bc6002
log insert error for add token
aneeshsharma 8533b6c
Fix code style issues with gofmt
lint-action 5197343
implemented authentication token middleware
aneeshsharma dbc72e5
Fix code style issues with gofmt
lint-action beeae61
explaning comments
aneeshsharma 6b9bfb4
Fix code style issues with gofmt
lint-action de112cf
Update authorization with main (#20)
aneeshsharma 5f022f8
Merge branch 'main' into authorization
aneeshsharma 8db5c18
use 'uid' as a constant
aneeshsharma d031da7
Merge branch 'authorization' of github.com:SimplQ/simplQ-golang into …
aneeshsharma 5f24ab8
renamed common.go to middleware.go for authentication package
aneeshsharma f6345bf
Fix code style issues with gofmt
lint-action 4cd7791
made getJWTValidator private
aneeshsharma 27032cb
Merge branch 'authorization' of github.com:SimplQ/simplQ-golang into …
aneeshsharma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,5 +21,5 @@ build/ | |
# temporary build files create by air | ||
tmp/ | ||
|
||
# dotenv variables | ||
# env file | ||
.env | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
package authentication | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
"strings" | ||
"time" | ||
|
||
"github.com/auth0/go-jwt-middleware/v2/jwks" | ||
"github.com/auth0/go-jwt-middleware/v2/validator" | ||
) | ||
|
||
// Prefix of the authorization header for an anonymous user | ||
const ANONYMOUS_PREFIX = "Anonymous" | ||
|
||
// Prefix of the authorization header for an authenticated user | ||
const BEARER_PREFIX = "Bearer" | ||
|
||
// Key for the "uid" stored in context | ||
const UID = "uid" | ||
|
||
// Authentication Middleware | ||
// Calls the next handler with `uid` in the `context` which can be used as a unique | ||
// id for any user. | ||
// Returns `http.StatusUnauthorized` to the client if the authorization token is not | ||
// found or is invalid. | ||
func AuthMiddleware(next http.Handler) http.Handler { | ||
tokenValidator := getJWTValidator() | ||
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
authorization_header := r.Header.Get("Authorization") | ||
|
||
// Default error message | ||
errorMessage := "Invalid authorization" | ||
|
||
if strings.HasPrefix(authorization_header, ANONYMOUS_PREFIX) { | ||
// For anonymous authentication | ||
|
||
// Get the token from the header | ||
uid := strings.Split(authorization_header, ANONYMOUS_PREFIX)[1] | ||
uid = strings.Trim(uid, " \n\r") | ||
|
||
// If a valid token is present | ||
if len(uid) > 0 { | ||
// Add given token as uid to the context | ||
ctx := context.WithValue(r.Context(), UID, uid) | ||
next.ServeHTTP(w, r.WithContext(ctx)) | ||
return | ||
} | ||
|
||
errorMessage = "Anonymous token not found" | ||
} else if strings.HasPrefix(authorization_header, BEARER_PREFIX) { | ||
// For bearer authentication | ||
|
||
// Get the JWT token from the header | ||
token := strings.Split(authorization_header, BEARER_PREFIX)[1] | ||
token = strings.Trim(token, " \n\r") | ||
|
||
// if a token is present | ||
if len(token) > 0 { | ||
// Validate the JWT token and get claims | ||
tokenDecoded, err := tokenValidator.ValidateToken(context.TODO(), token) | ||
|
||
if err == nil { | ||
tokenDecoded := tokenDecoded.(*validator.ValidatedClaims) | ||
|
||
// Use the "sub" claim as the uid | ||
uid := tokenDecoded.RegisteredClaims.Subject | ||
|
||
// if a valid uid is present | ||
if len(uid) > 0 { | ||
// Add the given "sub" as the uid to the context | ||
ctx := context.WithValue(r.Context(), UID, uid) | ||
next.ServeHTTP(w, r.WithContext(ctx)) | ||
return | ||
} | ||
} else { | ||
log.Println(err) | ||
} | ||
} | ||
errorMessage = "Invalid authentication token" | ||
} | ||
|
||
// If the next handler wasn't called, authentication failed | ||
// return Unauthorized http error | ||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(http.StatusUnauthorized) | ||
w.Write([]byte(fmt.Sprintf(`{"message": "%s"}`, errorMessage))) | ||
}) | ||
} | ||
|
||
// Returns a JWT Token validator | ||
func getJWTValidator() *validator.Validator { | ||
issuerURL, err := url.Parse("https://" + os.Getenv("AUTH0_DOMAIN") + "/") | ||
if err != nil { | ||
log.Fatalf("Failed to parse the issuer url: %v", err) | ||
} | ||
|
||
provider := jwks.NewCachingProvider(issuerURL, 5*time.Minute) | ||
|
||
jwtValidator, err := validator.New( | ||
provider.KeyFunc, | ||
validator.RS256, | ||
issuerURL.String(), | ||
[]string{os.Getenv("AUTH0_AUDIENCE")}, | ||
validator.WithAllowedClockSkew(time.Minute), | ||
) | ||
|
||
if err != nil { | ||
log.Fatalf("Failed to set up the jwt validator") | ||
} | ||
|
||
return jwtValidator | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why should this be gitignored?
If it's okay, let's checkin the default .env file, it will be easier for others to run the code my making minimal edits.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It shouldn't be a problem right now. But since we also store secrets as env variables, I just added it to gitignore. Also, I think generally most projects keep
.env
in.gitignore
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would be better to store these values as constants inside a go file instead of committing the
.env
file to git.