【问题标题】:Composure + Swagger with basic authentication带有基本身份验证的 Composure + Swagger
【发布时间】:2020-06-08 03:37:35
【问题描述】:

我正在尝试通过非常简单的基本身份验证使用 compojure 和 swagger 创建 Web 服务。我希望身份验证是单一的,例如,“mylogin”和“mypassword”用于登录名和密码。到目前为止,我所拥有的是

(ns my-api.handler
  (:require [compojure.api.sweet :refer :all]
            [ring.util.http-response :refer :all]
            [schema.core :as s]))

(s/defschema Request
  {:SomeData s/Str})

(s/defschema Result
  {:Results s/Str})

(defn dummy-return [request]
  {:Results "This is a dummy return"})

(def app
  (api
   {:swagger
    {:ui "/"
     :spec "/swagger.json"
     :data {:info {:title "A testing API"
                   :description "Compojure Api example"}
            :tags [{:name "api", :description "some apis"}]}}}

   (context "/api" []
     :tags ["api"]
     (POST "/API-Example" []
       :body [request Request]
       :return Result
       :summary "I want this to have a fixed basic authentication"
       (ok (dummy-return request))))))

它按预期工作。但是我如何为一个固定用户制作具有基本身份验证的相同 API 呢?我来自 python,使用 Flask 很容易做到这一点。我想知道是否有一个简单而优雅的解决方案而不会太冗长。

我尝试在与:data 相同的级别中包含一些诸如:securityDefinitions {:login {:type "basic" :password "test"}} 之类的内容,但即使不对其进行身份验证,我也可以调用该API。

我从lein new compojure-api my-api开始这个项目

感谢您的帮助!

【问题讨论】:

    标签: clojure basic-authentication compojure


    【解决方案1】:

    您可以添加提供基本身份验证的 Ring 处理程序。例如ring-basic-authentication

    您将处理程序全局添加到您的应用中,如下所示:

    (require '[ring.middleware.basic-authentication :refer [wrap-basic-authentication]])
    
    (defn authenticated? [username pass]
      (and (= username "foo")
           (= pass "bar")))
    
    (def app 
       (-> routes
           ..
           (wrap-basic-authentication authenticated?))
    

    【讨论】:

    • 谢谢!有效!我不知道这是否太明显,但为了帮助未来的初学者,在答案中,“路线”在我的示例中是“api”级别的所有内容
    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2018-01-24
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多