headers.go 863 B

12345678910111213141516171819202122232425262728293031
  1. package rest
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. // IsAuthenticated returns true if the bearer token in a request's authorization is equal to a user-defined token.
  7. // This function always returns true if the user-defined token is empty i.e. no authentication required.
  8. func IsAuthenticated(req *http.Request, token string) bool {
  9. if token == "" {
  10. return true
  11. }
  12. read := ReadBearerToken(req)
  13. return read == token
  14. }
  15. // ReadBearerToken reads the token portion of a bearer token in a request's authorization header.
  16. // This function returns an empty string if the header is not provided or is not a bearer token.
  17. func ReadBearerToken(req *http.Request) string {
  18. header := req.Header.Get("authorization")
  19. if len(header) > 8 {
  20. bearer := header[0:7]
  21. fmt.Println(bearer)
  22. if bearer == "bearer " || bearer == "Bearer " {
  23. return header[7:]
  24. }
  25. }
  26. return ""
  27. }