/
authn.clj
51 lines (43 loc) · 2.1 KB
/
authn.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(ns keycloak.authn
(:require
[clojure.tools.logging :as log :refer [info]]
[clj-http.client :as http]
[cheshire.core :refer [parse-string]]
[keycloak.deployment :as deployment]))
;(set! *warn-on-reflection* true)
(defn oidc-connect-url [auth-server-url realm-name]
(str auth-server-url "/realms/" realm-name "/protocol/openid-connect/token"))
(defn client-credentials
([client-id username password]
{:grant_type "password"
:client_id client-id
:username username
:password password})
([client-id client-secret]
{:grant_type "client_credentials"
:client_id client-id
:client_secret client-secret}))
(defn authenticate
"return the bearer token decoded as a clojure data struct. (with :access_token and :refresh_token keys, beware 'underscore _' not 'hyphen -')"
([{:keys [auth-server-url realm client-id] :as conf} client-secret]
(authenticate auth-server-url realm client-id client-secret))
([{:keys [auth-server-url realm client-id] :as conf} username password]
(authenticate auth-server-url realm client-id username password))
([auth-server-url realm client-id client-secret]
(info "Authenticate against" (oidc-connect-url auth-server-url realm) "for client-id" client-id)
(-> (http/post (oidc-connect-url auth-server-url realm)
{:form-params (client-credentials client-id client-secret)})
:body
(parse-string true)))
([auth-server-url realm client-id username password]
(info "Authenticate against" (oidc-connect-url auth-server-url realm) "for client-id" client-id "with user" username)
(-> (http/post (oidc-connect-url auth-server-url realm)
{:form-params (client-credentials client-id username password)})
:body
(parse-string true))))
(defn access-token [^org.keycloak.authorization.client.AuthzClient client username password]
(-> client (.obtainAccessToken username password)))
(defn auth-cookie [bearer]
{"X-Authorization-Token" {:discard true, :path "/", :value (:access_token bearer), :version 0}})
(defn auth-header [bearer]
{"authorization" (str "Bearer " (:access_token bearer))})