// AddLoginRequiredHeaderToUnauthorizedError adds "WWW-Authenticate: LOGIN" header to the response
// if the error is UnauthorizedError
508862
func (m *tokenManager) AddLoginRequiredHeaderToUnauthorizedError(err error, rw http.ResponseWriter) {
	if unth, _ := autherrors.IsUnauthorizedError(err); unth {
		m.AddLoginRequiredHeader(rw)
	}
}
334698
func (s *RequestHeaderAuthenticationOptions) ToAuthenticationRequestHeaderConfig() *authenticatorfactory.RequestHeaderConfig {
	if len(s.ClientCAFile) == 0 {
		return nil
	}

	return &authenticatorfactory.RequestHeaderConfig{
		UsernameHeaders:     s.UsernameHeaders,
		GroupHeaders:        s.GroupHeaders,
		ExtraHeaderPrefixes: s.ExtraHeaderPrefixes,
		ClientCA:            s.ClientCAFile,
		AllowedClientNames:  s.AllowedNames,
	}
}
1364916
func AuthorizationHeader(creds *common.Credentials) (key, value string) {
	return "Authorization", "Bearer " + creds.Get(OAuth2KeyAccessToken).Str("Invalid")
}
28664
func NewAuthenticatedClient() Client {
	authenticator := newMockAuthenticator(func(request *http.Request) error {
		request.Header.Set("Authorization", "fake-authorization")
		return nil
	})

	return NewClient(authenticator)
}
714698
func AuthTokenNonBlocking() (string, error) {
	cond.RLock()
	defer cond.RUnlock()
	if currentToken == "" {
		return "", ErrNotAuthenticated
	}

	if expired() {
		return "", ErrIdentityTokenExpired
	}

	return currentToken, nil
}
42973
func handleUnauthorized(w http.ResponseWriter, r *http.Request, rule Rule, realm string) int {
	if rule.Redirect != "" {
		replacer := httpserver.NewReplacer(r, nil, "")
		http.Redirect(w, r, replacer.Replace(rule.Redirect), http.StatusSeeOther)
		return http.StatusSeeOther
	}

	w.Header().Add("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"%s\",error=\"invalid_token\"", realm))
	return http.StatusUnauthorized
}
1083176
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))
	b.opts.UnauthorizedHandler.ServeHTTP(w, r)
}
69690
func (ac authChallenge) SetHeaders(r *http.Request, w http.ResponseWriter) {
	w.Header().Add("WWW-Authenticate", ac.challengeParams(r))
}
884040
func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	username := r.FormValue("username")
	password := r.FormValue("password")
	linkingToken := r.FormValue("account_linking_token")
	rawRedirect := r.FormValue("redirect_uri")

	if !checkCredentials(username, password) {
		fmt.Fprint(w, templateLogin(loginPath, linkingToken, rawRedirect, true))
		return
	}

	redirectURL, err := url.Parse(rawRedirect)
	if err != nil {
		log.Println("failed to parse url:", err)
		return
	}

	q := redirectURL.Query()
	q.Set("authorization_code", "something")
	redirectURL.RawQuery = q.Encode()

	w.Header().Set("Location", redirectURL.String())
	w.WriteHeader(http.StatusFound)
}
666691
func WrapAuth(auth Authenticater, handle http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if auth.Authenticate(r) {
			handle(w, r)
		} else {
			w.WriteHeader(http.StatusUnauthorized)
		}
	}
}
296511
func (c *Client) IsAuthenticated() bool {
	authHeader, ok := c.Headers["Authorization"]

	if !ok || (ok && authHeader == "token ") {
		return false
	}

	return true
}
945434
func AddDeprecatedHeader(r *http.Request, token string) {
	if len(token) > 0 {
		r.Header.Add(DeprecatedAuthHeader, token)
	}
}
625960
func (t *Token) SetAuthHeader(r *http.Request) {
	r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
}
1022568
func (auth *Auth) RequestHeader() string {
	auth.MAC = auth.mac(AuthHeader)

	h := `Hawk id="` + auth.Credentials.ID +
		`", mac="` + base64.StdEncoding.EncodeToString(auth.MAC) +
		`", ts="` + strconv.FormatInt(auth.Timestamp.Unix(), 10) +
		`", nonce="` + auth.Nonce + `"`

	if len(auth.Hash) > 0 {
		h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"`
	}
	if auth.Ext != "" {
		h += `, ext="` + auth.Ext + `"`
	}
	if auth.Credentials.App != "" {
		h += `, app="` + auth.Credentials.App + `"`
	}
	if auth.Credentials.Delegate != "" {
		h += `, dlg="` + auth.Credentials.Delegate + `"`
	}

	return h
}
1320931
func (m *middleware) validateHeader(r *http.Request, auth string) (context.Context, *Error) {
	var f = strings.Fields(auth)
	if len(f) != 2 {
		return nil, ErrBadAuthorizationHeader
	}

	var scheme = strings.ToLower(f[0])
	var token = f[1]

	switch scheme {
	case schemeBasic:
		return m.validateBasicAuth(r)
	case schemeBearer:
		return m.validateJWT(r, token)
	default:
		return nil, ErrUnsupportedAuthScheme
	}
}
1071246
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) {
	authReq, err := s.parseAuthorizationRequest(r)
	if err != nil {
		s.logger.Errorf("Failed to parse authorization request: %v", err)
		if handler, ok := err.Handle(); ok {
			// client_id and redirect_uri checked out and we can redirect back to
			// the client with the error.
			handler.ServeHTTP(w, r)
			return
		}

		// Otherwise render the error to the user.
		//
		// TODO(ericchiang): Should we just always render the error?
		s.renderError(w, err.Status(), err.Error())
		return
	}

	// TODO(ericchiang): Create this authorization request later in the login flow
	// so users don't hit "not found" database errors if they wait at the login
	// screen too long.
	//
	// See: https://github.com/dexidp/dex/issues/646
	authReq.Expiry = s.now().Add(s.authRequestsValidFor)
	if err := s.storage.CreateAuthRequest(authReq); err != nil {
		s.logger.Errorf("Failed to create authorization request: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.")
		return
	}

	connectors, e := s.storage.ListConnectors()
	if e != nil {
		s.logger.Errorf("Failed to get list of connectors: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.")
		return
	}

	if len(connectors) == 1 {
		for _, c := range connectors {
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound)
			return
		}
	}

	connectorInfos := make([]connectorInfo, len(connectors))
	i := 0
	for _, conn := range connectors {
		connectorInfos[i] = connectorInfo{
			ID:   conn.ID,
			Name: conn.Name,
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID,
		}
		i++
	}

	if err := s.templates.login(w, connectorInfos); err != nil {
		s.logger.Errorf("Server template error: %v", err)
	}
}
400562
func AddRequestIdHeader(r *http.Request, token string) {
	if len(token) > 0 {
		r.Header.Add(RequestHeaderKey, token)
	}
}