restful-basic-authentication.go 965 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. "github.com/emicklei/go-restful"
  4. "io"
  5. "net/http"
  6. )
  7. // This example shows how to create a (Route) Filter that performs Basic Authentication on the Http request.
  8. //
  9. // GET http://localhost:8080/secret
  10. // and use admin,admin for the credentials
  11. func main() {
  12. ws := new(restful.WebService)
  13. ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret))
  14. restful.Add(ws)
  15. http.ListenAndServe(":8080", nil)
  16. }
  17. func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
  18. encoded := req.Request.Header.Get("Authorization")
  19. // usr/pwd = admin/admin
  20. // real code does some decoding
  21. if len(encoded) == 0 || "Basic YWRtaW46YWRtaW4=" != encoded {
  22. resp.AddHeader("WWW-Authenticate", "Basic realm=Protected Area")
  23. resp.WriteErrorString(401, "401: Not Authorized")
  24. return
  25. }
  26. chain.ProcessFilter(req, resp)
  27. }
  28. func secret(req *restful.Request, resp *restful.Response) {
  29. io.WriteString(resp, "42")
  30. }