/*
SSOHandler offers the users the flexibility of choosing which http handlers
need JWT validation.
*/
183514
func (a *oauth) SSOHandler(p string, h func(http.ResponseWriter, *http.Request)) (string, httprouter.Handle) {
	return p, a.VerifyOAuth(alice.New().ThenFunc(h))
}
1127476
func (a *Auth) Handler(h http.Handler) http.Handler {
	a.ensureDefaults()
	return &handler{Auth: a, handler: h}
}
1067565
func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) {
	return &HTTPHandlerSwitcher{
		handler: safe.New(newHandler),
	}
}
64242
func (mw *JWTMiddleware) LoginHandler(writer rest.ResponseWriter, request *rest.Request) {
	loginVals := login{}
	err := request.DecodeJsonPayload(&loginVals)

	if err != nil {
		mw.unauthorized(writer)
		return
	}

	if !mw.Authenticator(loginVals.Username, loginVals.Password) {
		mw.unauthorized(writer)
		return
	}

	token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))

	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(loginVals.Username) {
			token.Claims[key] = value
		}
	}

	token.Claims["id"] = loginVals.Username
	token.Claims["exp"] = time.Now().Add(mw.Timeout).Unix()
	if mw.MaxRefresh != 0 {
		token.Claims["orig_iat"] = time.Now().Unix()
	}
	tokenString, err := token.SignedString(mw.Key)

	if err != nil {
		mw.unauthorized(writer)
		return
	}

	writer.WriteJson(resultToken{Token: tokenString})
}
417722
func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
	handler := &tokenHandler{
		transport:     options.Transport,
		creds:         options.Credentials,
		offlineAccess: options.OfflineAccess,
		forceOAuth:    options.ForceOAuth,
		clientID:      options.ClientID,
		scopes:        options.Scopes,
		clock:         realClock{},
		logger:        options.Logger,
	}

	return handler
}
1046233
func (p *Layer) SetHandler(phase string, handler context.HandlerFunc) {
	p.Handlers[phase] = handler
}
1101641
func (m *AuthMethod) logoutHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	dest, err := normalizeURL(r.URL.Query().Get("r"))
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Close a session if there's one.
	sid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}
	if sid != "" {
		(logging.Fields{"sid": sid}).Infof(c, "Closing the session")
		if err = m.SessionStore.CloseSession(c, sid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Nuke all session cookies to get to a completely clean state.
	removeCookie(rw, r, sessionCookieName)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}
1074257
func (s *Server) HTTPHandler() http.Handler {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.httpHandler
}
512064
func BasicAuthHandler(h http.Handler) http.Handler {
	f := func(w http.ResponseWriter, req *http.Request) {
		if Authorised == nil {
			h.ServeHTTP(w, req)
			return
		}

		u, pw, ok := req.BasicAuth()
		if !ok || !Authorised(u, pw) {
			w.Header().Set("WWW-Authenticate", "Basic")
			w.WriteHeader(401)
			return
		}
		h.ServeHTTP(w, req)
	}

	return http.HandlerFunc(f)
}
321046
func NewHandler(validator Validator) (http.Handler, error) {
	log.Info("setting up key / CSR generator")
	return &api.HTTPHandler{
		Handler: &Handler{
			generator: &csr.Generator{Validator: validator},
		},
		Methods: []string{"POST"},
	}, nil
}
469421
func ValidateAuthTokenWithJWT(
	ctx types.Context,
	config *types.AuthConfig,
	encJWT string) (*types.AuthToken, error) {

	lf := map[string]interface{}{"encJWT": encJWT}
	ctx.WithFields(lf).Debug("validating jwt")

	jwt, err := jws.ParseJWT([]byte(encJWT))
	if err != nil {
		ctx.WithFields(lf).WithError(err).Error("error parsing jwt")
		return nil, &types.ErrSecTokInvalid{InvalidToken: true, InnerError: err}
	}

	sm := parseSigningMethod(config.Alg)
	lf["signingMethod"] = sm.Alg()
	ctx.WithFields(lf).Debug("parsed jwt signing method")

	if err := jwt.Validate(config.Key, sm); err != nil {
		ctx.WithFields(lf).WithError(err).Error("error validating jwt")
		return nil, &types.ErrSecTokInvalid{InvalidSig: true, InnerError: err}
	}

	ctx.WithFields(lf).Debug("validated jwt signature")

	if len(jwt.Claims()) == 0 {
		ctx.WithFields(lf).Error("jwt missing claims")
		return nil, &types.ErrSecTokInvalid{}
	}

	var (
		sub string
		iat time.Time
		exp time.Time
		nbf time.Time
		ok  bool
	)

	if sub, ok = jwt.Claims().Subject(); !ok {
		ctx.WithFields(lf).Error("jwt missing sub claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "sub"}
	}

	if iat, ok = jwt.Claims().IssuedAt(); !ok {
		ctx.WithFields(lf).Error("jwt missing iat claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "iat"}
	}

	if exp, ok = jwt.Claims().Expiration(); !ok {
		ctx.WithFields(lf).Error("jwt missing exp claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "exp"}
	}

	if nbf, ok = jwt.Claims().NotBefore(); !ok {
		ctx.WithFields(lf).Error("jwt missing nbf claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "nbf"}
	}

	tok := &types.AuthToken{
		Subject:   sub,
		IssuedAt:  iat.UTC().Unix(),
		Expires:   exp.UTC().Unix(),
		NotBefore: nbf.UTC().Unix(),
	}

	lf["sub"] = tok.Subject
	lf["iat"] = tok.IssuedAt
	lf["exp"] = tok.Expires
	lf["nbf"] = tok.NotBefore

	if err := validateAuthTokenAllowed(ctx, config, lf, tok); err != nil {
		return nil, err
	}

	ctx.WithFields(lf).Info("validated security token")
	return tok, nil
}
827283
func (p *Processor) SetHandler(msg interface{}, msgHandler MsgHandler) {
	msgType := reflect.TypeOf(msg)
	if msgType == nil || msgType.Kind() != reflect.Ptr {
		log.Fatal("json message pointer required")
	}
	msgID := msgType.Elem().Name()
	i, ok := p.msgInfo[msgID]
	if !ok {
		log.Fatal("message %v not registered", msgID)
	}

	i.msgHandler = msgHandler
}
1049440
func NewAuthSessionHandler(sessionStorage session.Storage, must bool) func(http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return &authHandler{
			handler:    h,
			backend:    sessionStorage,
			contextKey: sessionKey,
			headerKey:  SessionHeader,
			mustAuth:   must,
		}
	}
}
1009269
func CreateHealthzHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
}
289139
func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		addCommonJwtRespHeaders(w, r)
		// Look for JWT in both headers and request value "access_token".
		token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
			// Token was signed with RSA method when it was initially granted
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
			}
			return publicKey, nil
		})
		if err != nil || !token.Valid {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}
		tokenClaims := token.Claims.(jwt.MapClaims)
		var url = strings.TrimPrefix(r.URL.Path, "/")
		var col = r.FormValue("col")
		// Call the API endpoint handler if authorization allows
		if tokenClaims[JWT_USER_ATTR] == JWT_USER_ADMIN {
			originalHandler(w, r)
			return
		}
		if !sliceContainsStr(tokenClaims[JWT_ENDPOINTS_ATTR], url) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if col != "" && !sliceContainsStr(tokenClaims[JWT_COLLECTIONS_ATTR], col) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}
		originalHandler(w, r)
	}
}
750046
func TokenHandler(cb AuthTokenHandler) Option {
	return func(o *Options) error {
		if o.Token != "" {
			return ErrTokenAlreadySet
		}
		o.TokenHandler = cb
		return nil
	}
}
587866
func (ch challenge) SetHeaders(r *http.Request, w http.ResponseWriter) {
	w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", ch.realm))
}