-
Notifications
You must be signed in to change notification settings - Fork 13
/
oauth2.clj
180 lines (165 loc) · 8.54 KB
/
oauth2.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
(ns geheimtur.impl.oauth2
(:require [clj-http.client :as client]
[clojure.walk :refer [keywordize-keys]]
[geheimtur.util.response :as response]
[geheimtur.util.auth :refer [authenticate]]
[io.pedestal.log :as log]
[io.pedestal.interceptor.helpers :as h]
[ring.util.codec :as ring-codec])
(:import [java.math BigInteger]
[java.security SecureRandom]))
(defn create-afs-token
"Creates a random state token to prevent request forgery."
[_]
(.toString (BigInteger. 130 (SecureRandom.)) 32))
(defn create-url
"Creates a URL from a url string and a map with query parameters."
[url query]
(->> query
ring-codec/form-encode
(str url (if (.contains url "?") "&" "?"))))
(defn authenticate-handler
"Creates a handler that redirects users to OAuth2 service providers using a providers configuration map or a function.
Example:
(def providers
{:github {:auth-url \"https://github.com/login/oauth/authorize\"
:client-id \"your-client-id\"
:client-secret \"your-client-secret\"
:scope \"user:email\"
:client-params {:foo \"bar\"}
:create-state-fn (fn [req] (generate-a-token req))
:check-state-fn (fn [context state token] (and state token (= state token)))
:token-url \"https://github.com/login/oauth/access_token\"
:token-parse-fn (fn [resp] (parse-string (:body resp)))
:user-info-url \"https://api.github.com/user\"
:user-info-parse-fn (fn [resp] (parse-string (:body resp)))
:on-success-handler on-github-success}})
The following keys in provider's configuration are optional:
:client-params - a map of extra query parameters to be included in the authorization request
:create-state-fn - a function that accepts the authentication request and returns a state token.
:check-state-fn - a function that accepts the context, the state token in the callback request,
and the one stored in the session and returns true if they match.
:token-parse-fn - a function that accepts the token endpoint response and returns a map with the parsed
OAuth2 token response. The successfuly parsed response must have at least :access_token key.
:user-info-url - if defined, will be used to get user's details after successful access token acquisition
:user-info-parse-fn - if defined, will be applied to the response of user's details endpoint
:on-success-handler - a function that accepts a request context and an obtained identity/access token map and returns a correct ring response.
It is called only if an identity/access token is resolved."
[providers-map-or-fn]
{:pre [(or (map? providers-map-or-fn) (fn? providers-map-or-fn))]}
(h/handler
::authenticate-handler
(fn [req]
(let [{:keys [query-params] :as request} req
providers (if (fn? providers-map-or-fn) (providers-map-or-fn) providers-map-or-fn)]
(when-let [provider (:provider query-params)]
(when-let [{:keys [auth-url
client-id
scope
callback-uri
client-params
create-state-fn]
:or {create-state-fn
create-afs-token}} (get providers (keyword provider))]
(let [token (create-state-fn request)
query (merge client-params {:client_id client-id
:response_type "code"
:scope scope
:state token})
query (if callback-uri
(assoc query :redirect_uri callback-uri)
query)
path (or (:return query-params) "/")]
(-> (create-url auth-url query)
(response/redirect)
(assoc-in [:session ::callback-state] {:return path
:token token
:provider provider})))))))))
(defn fetch-token
"Fetches an OAuth access token using the given code and provider's configuration."
[code {:keys [token-url client-id client-secret callback-uri token-parse-fn] :as provider}]
(let [query {:code code
:client_id client-id
:client_secret client-secret
:grant_type "authorization_code"}
query (if callback-uri
(assoc query :redirect_uri callback-uri)
query)]
(try
(let [response (client/post token-url {:form-params query
:throw-entire-message? true
:as (when (nil? token-parse-fn) :auto)})]
(when (client/success? response)
(if (nil? token-parse-fn)
(:body response)
(token-parse-fn response))))
(catch Exception ex
(log/warn :msg (str "Could not fetch OAuth access token from " token-url)
:exception ex)
nil))))
(defn fetch-user-info
[token url response-parse-fn]
"Fetches user's details using the given URL and an OAuth access token.
Accepts:
token - an OAuth token to be used to fetch the user details
url - a URL to fetch user details from
response-parse-fn - a function to be used to parse the response of the endpoint (optional)"
(try
(let [response (client/get url {:oauth-token token
:throw-entire-message? true
:as (when (nil? response-parse-fn) :auto)})]
(if (nil? response-parse-fn)
(:body response)
(response-parse-fn response)))
(catch Exception ex
(log/warn :msg (str "Could not fetch user details from " url)
:exception ex)
nil)))
(defn resolve-identity
"Resolves user's identity based on provider's configuration.
Accepts:
token - an OAuth access token response. Must contain at least :access_token.
provider - a provider's configuration"
[{:keys [access_token expires_in refresh_token] :as token}
{:keys [user-info-url user-info-parse-fn]}]
(when access_token
(let [result {:access-token access_token
:expires-in expires_in
:refresh-token refresh_token}]
(if user-info-url
(when-let [user-info (fetch-user-info access_token user-info-url user-info-parse-fn)]
(assoc result :identity user-info))
result))))
(defn- process-callback
[code provider]
(when-let [token (fetch-token code provider)]
(resolve-identity token provider)))
(defn- default-check-state-fn
"Verifies that state and token are non-nil, and match."
[_ state token]
(and state token
(= state token)))
(defn callback-handler
"Creates an OAuth callback handler using on a service providers configuration map or a function.
If authentication flow fails for any reason, the user will be redirected to /unauthorized url."
[providers-map-or-fn]
{:pre [(or (map? providers-map-or-fn) (fn? providers-map-or-fn))]}
(h/before
::callback-handler
(fn [{request :request :as context}]
(let [{:keys [query-params session]} request
{:keys [state code]} query-params
{:keys [return token provider]} (::callback-state session)
providers (if (fn? providers-map-or-fn) (providers-map-or-fn) providers-map-or-fn)
{:keys [on-success-handler
check-state-fn] :as p
:or {check-state-fn
default-check-state-fn}} (get providers (keyword provider))]
(assoc context :response
(if (and code return provider p (check-state-fn context state token))
(if-let [identity (process-callback code p)]
(if on-success-handler
(on-success-handler context (assoc identity :return return))
(authenticate (response/redirect return) identity))
(response/redirect "/unauthorized"))
(response/redirect "/unauthorized")))))))