Exemple #1
0
func (m *Middleware) IsAuthenticated(next chd.ContextHandler) chd.ContextHandler {
	return chd.ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
		bearer := osin.CheckBearerAuth(req)
		if bearer == nil {
			log.WithFields(log.Fields{
				"authentication": "invalid",
				"error":          errors.New("No bearer token given"),
				"valid":          false,
			}).Warn(`Authentication invalid.`)
			rw.WriteHeader(http.StatusUnauthorized)
			return
		}
		if authenticated, err := m.Client.IsAuthenticated(bearer.Code); err != nil {
			log.WithFields(log.Fields{
				"authentication": "invalid",
				"error":          err,
				"valid":          authenticated,
			}).Warn(`Authentication invalid.`)
			rw.WriteHeader(http.StatusUnauthorized)
			return
		} else if !authenticated {
			log.WithFields(log.Fields{
				"authentication": "invalid",
				"error":          nil,
				"valid":          authenticated,
			}).Warn(`Authentication invalid.`)
			rw.WriteHeader(http.StatusUnauthorized)
			return
		}

		log.WithFields(log.Fields{"authentication": "success"}).Info(`Authenticated.`)
		next.ServeHTTPContext(ctx, rw, req)
	})
}
Exemple #2
0
// RequireLogin middleware checks if request has a valid access token
func RequireLogin(authServer *osin.Server) gin.HandlerFunc {
	return func(c *gin.Context) {
		bearer := osin.CheckBearerAuth(c.Request)
		// no token in request
		if bearer == nil {
			c.Header("WWW-Authenticate", `Bearer`)
			c.AbortWithStatus(http.StatusUnauthorized)
		} else {
			// load token from storage
			accessData, err := authServer.Storage.LoadAccess(bearer.Code)
			// token not found
			if err != nil {
				c.Header("WWW-Authenticate", `Bearer, error="invalid_token"`)
				c.AbortWithStatus(http.StatusUnauthorized)
			} else {
				if accessData.IsExpired() {
					c.Header("WWW-Authenticate", `Bearer, error="invalid_token", error_description="The access token expired"`)
					c.AbortWithStatus(http.StatusUnauthorized)
				} else {
					// set user data into request
					c.Set("user", accessData.UserData)
					c.Next()
				}
			}
		}
	}
}
Exemple #3
0
func (c *HTTPClient) IsRequestAllowed(req *http.Request, resource, permission, owner string) (bool, error) {
	var token *osin.BearerAuth
	if token = osin.CheckBearerAuth(req); token == nil {
		return false, errors.New("No token given.")
	} else if token.Code == "" {
		return false, errors.New("No token given.")
	}
	env := middleware.NewEnv(req)
	env.Owner(owner)
	return c.IsAllowed(&AuthorizeRequest{Token: token.Code, Resource: resource, Permission: permission, Context: env.Ctx()})
}
Exemple #4
0
func (h *Handler) IntrospectHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	bearer := osin.CheckBearerAuth(r)
	if bearer == nil {
		log.WithField("introspect", "fail").Warn("No authorization header given.")
		http.Error(w, "No bearer given.", http.StatusUnauthorized)
		return
	} else if bearer.Code == "" {
		log.WithField("introspect", "fail").Warn("No authorization bearer is empty.")
		http.Error(w, "No bearer token given.", http.StatusUnauthorized)
		return
	}

	token, err := h.JWT.VerifyToken([]byte(bearer.Code))
	if err != nil {
		log.WithField("introspect", "fail").Warn("Bearer token is invalid.")
		http.Error(w, "Bearer token is not valid.", http.StatusForbidden)
		return
	}

	result := token.Claims
	defer func() {
		out, err := json.Marshal(result)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write(out)
	}()

	result["active"] = false
	claims := jwt.ClaimsCarrier(token.Claims)
	if claims.GetAudience() != h.Audience {
		log.WithFields(log.Fields{
			"introspect": "fail",
			"expted":     h.Audience,
			"actual":     claims.GetAudience(),
		}).Warn(`Token audience mismatch.`)
		return
	} else {
		result["active"] = token.Valid
		return
	}
}
Exemple #5
0
func (m *Middleware) IsAuthorized(resource, permission string, environment *middleware.Env) func(chd.ContextHandler) chd.ContextHandler {
	return func(next chd.ContextHandler) chd.ContextHandler {
		return chd.ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
			if environment == nil {
				environment = middleware.NewEnv(req)
			}

			bearer := osin.CheckBearerAuth(req)
			if allowed, err := m.Client.IsAllowed(&AuthorizeRequest{
				Resource:   resource,
				Permission: permission,
				Context:    environment.Ctx(),
				Token:      bearer.Code,
			}); err != nil {
				log.WithFields(log.Fields{
					"authorization": "forbidden",
					"error":         err,
					"valid":         allowed,
					"permission":    permission,
					"resource":      resource,
				}).Warnf(`Subject is not allowed perform this action on this resource.`)
				rw.WriteHeader(http.StatusForbidden)
				return
			} else if !allowed {
				log.WithFields(log.Fields{
					"authorization": "forbidden",
					"error":         nil,
					"valid":         allowed,
					"permission":    permission,
					"resource":      resource,
				}).Warnf(`Subject is not allowed perform this action on this resource.`)
				rw.WriteHeader(http.StatusForbidden)
				return
			}

			log.WithFields(log.Fields{"authorization": "success"}).Info(`Allowed!`)
			next.ServeHTTPContext(ctx, rw, req)
		})
	}
}
Exemple #6
0
func NewContextFromAuthorization(ctx context.Context, req *http.Request, j *hjwt.JWT, p policy.Storage) context.Context {
	bearer := osin.CheckBearerAuth(req)
	if bearer == nil {
		log.Warn("No authorization bearer given.")
		return NewContextFromAuthValues(ctx, nil, nil, nil)
	}

	t, err := j.VerifyToken([]byte(bearer.Code))
	if err != nil {
		log.Warnf(`Token validation errored: "%v".`, err)
		return NewContextFromAuthValues(ctx, nil, nil, nil)
	} else if !t.Valid {
		log.Warn("Token is invalid.")
		return NewContextFromAuthValues(ctx, nil, nil, nil)
	}

	claims := hjwt.ClaimsCarrier(t.Claims)
	user := claims.GetSubject()
	if user == "" {
		log.Warnf(`sub claim may not be empty, to: "%v".`, t.Claims)
		return NewContextFromAuthValues(ctx, nil, nil, nil)
	}

	policies, err := p.FindPoliciesForSubject(user)
	if err != nil {
		log.Warnf(`Policies for "%s" could not be retrieved: "%v"`, user, err)
		return NewContextFromAuthValues(ctx, nil, nil, nil)
	}

	//	user, err := s.Get(id)
	//	if err != nil {
	//		log.Warnf("Subject not found in store: %v %v", t.Claims, err)
	//		return NewContextFromAuthValues(ctx, nil, nil, nil)
	//	}

	return NewContextFromAuthValues(ctx, claims, t, policies)
}