headers.go 834 B

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