Skip to content

Commit 53ade6b

Browse files
BobbyMcWhoJesse Doyle
authored andcommitted
Minor refactor of pkce
1 parent 13dde0c commit 53ade6b

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

lib/omniauth/strategies/oauth2.rb

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@ def self.inherited(subclass)
3030
option :auth_token_params, {}
3131
option :provider_ignores_state, false
3232
option :pkce, false
33+
option :pkce_verifier, nil
34+
option :pkce_options, {
35+
:code_challenge => proc { |verifier|
36+
Base64.urlsafe_encode64(
37+
Digest::SHA2.digest(verifier),
38+
padding: false
39+
)
40+
},
41+
:code_challenge_method => "S256"
42+
}
3343

3444
attr_accessor :access_token
3545

@@ -50,19 +60,20 @@ def request_phase
5060
end
5161

5262
def authorize_params
53-
verifier = SecureRandom.hex(64)
54-
55-
pkce_authorize_params!(verifier)
56-
5763
options.authorize_params[:state] = SecureRandom.hex(24)
58-
params = options.authorize_params.merge(options_for("authorize"))
5964

6065
if OmniAuth.config.test_mode
6166
@env ||= {}
6267
@env["rack.session"] ||= {}
6368
end
6469

65-
build_authorize_session!(params, verifier)
70+
params = options.authorize_params
71+
.merge(options_for("authorize"))
72+
.merge(pkce_authorize_params)
73+
74+
session["omniauth.pkce.verifier"] = options.pkce_verifier if options.pkce
75+
session["omniauth.state"] = params[:state]
76+
6677
params
6778
end
6879

@@ -91,21 +102,16 @@ def callback_phase # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexi
91102

92103
protected
93104

94-
def build_authorize_session!(params, verifier)
95-
session["omniauth.pkce.verifier"] = verifier if options.pkce
96-
session["omniauth.state"] = params[:state]
97-
end
98-
99-
def pkce_authorize_params!(verifier)
100-
return unless options.pkce
105+
def pkce_authorize_params
106+
return {} unless options.pkce
107+
options.pkce_verifier = SecureRandom.hex(64)
101108

102109
# NOTE: see https://tools.ietf.org/html/rfc7636#appendix-A
103-
challenge = Base64
104-
.urlsafe_encode64(Digest::SHA2.digest(verifier))
105-
.split("=")
106-
.first
107-
options.authorize_params[:code_challenge] = challenge
108-
options.authorize_params[:code_challenge_method] = "S256"
110+
{
111+
:code_challenge => options.pkce_options[:code_challenge]
112+
.call(options.pkce_verifier),
113+
:code_challenge_method => options.pkce_options[:code_challenge_method]
114+
}
109115
end
110116

111117
def pkce_token_params

0 commit comments

Comments
 (0)