7 "github.com/justinas/alice"
8 sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic"
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
13func NewBasicAuthSessionLoader(validator basic.Validator) alice.Constructor {
14 return func(next http.Handler) http.Handler {
15 return loadBasicAuthSession(validator, next)
19// loadBasicAuthSession attmepts to load a session from basic auth credentials
20// stored in an Authorization header within the request.
21// If no authorization header is found, or the header is invalid, no session
22// will be loaded and the request will be passed to the next handler.
23// If a session was loaded by a previous handler, it will not be replaced.
24func loadBasicAuthSession(validator basic.Validator, next http.Handler) http.Handler {
25 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
26 scope := GetRequestScope(req)
27 // If scope is nil, this will panic.
28 // A scope should always be injected before this handler is called.
29 if scope.Session != nil {
30 // The session was already loaded, pass to the next handler
31 next.ServeHTTP(rw, req)
35 session, err := getBasicSession(validator, req)
37 logger.Errorf("Error retrieving session from token in Authorization header: %v", err)
40 // Add the session to the scope if it was found
41 scope.Session = session
42 next.ServeHTTP(rw, req)
46// getBasicSession attempts to load a basic session from the request.
47// If the credentials in the request exist within the htpasswdMap,
48// a new session will be created.
49func getBasicSession(validator basic.Validator, req *http.Request) (*sessionsapi.SessionState, error) {
50 auth := req.Header.Get("Authorization")
52 // No auth header provided, so don't attempt to load a session
56 user, password, err := findBasicCredentialsFromHeader(auth)
61 if validator.Validate(user, password) {
62 logger.PrintAuthf(user, req, logger.AuthSuccess, "Authenticated via basic auth and HTpasswd File")
63 return &sessionsapi.SessionState{User: user}, nil
66 logger.PrintAuthf(user, req, logger.AuthFailure, "Invalid authentication via basic auth: not in Htpasswd File")
70// findBasicCredentialsFromHeader finds basic auth credneitals from the
71// Authorization header of a given request.
72func findBasicCredentialsFromHeader(header string) (string, string, error) {
73 tokenType, token, err := splitAuthHeader(header)
78 if tokenType != "Basic" {
79 return "", "", fmt.Errorf("invalid Authorization header: %q", header)
82 user, password, err := getBasicAuthCredentials(token)
84 return "", "", fmt.Errorf("error decoding basic auth credentials: %v", err)
87 return user, password, nil
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list