Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Implement registering a WebAuthn device

Klaus Zanders3f686c91f886
diff --git a/frontend/src/stimulus/controllers/dynamic/two-factor-authentication.controller.ts b/frontend/src/stimulus/controllers/dynamic/two-factor-authentication.controller.ts
index fd1b2fe5267..480f37abcb4 100644
--- a/frontend/src/stimulus/controllers/dynamic/two-factor-authentication.controller.ts
+++ b/frontend/src/stimulus/controllers/dynamic/two-factor-authentication.controller.ts
@@ -28,37 +28,69 @@
* ++
*/
-import { Controller } from '@hotwired/stimulus';
-import QrCreator from 'qr-creator';
+import { Controller } from "@hotwired/stimulus";
+import * as WebAuthnJSON from "@github/webauthn-json/browser-ponyfill";
+import QrCreator from "qr-creator";
export default class TwoFactorAuthenticationController extends Controller {
- static targets = [
- 'resendOptions',
- 'qrCodeElement',
- ];
+ static targets = ["resendOptions", "qrCodeElement", "webauthnCredential"];
- declare readonly resendOptionsTarget:HTMLElement;
+ declare readonly resendOptionsTarget: HTMLElement;
+ declare readonly webauthnCredentialTarget: HTMLInputElement;
- qrCodeElementTargetConnected(target:HTMLElement) {
+ async onCreateDevice(event: Event) {
+ const data = (event.target as HTMLElement).dataset;
+
+ // We are not in the context of adding a WebAuthn device, so we can just submit the form
+ if (data.deviceType !== "webauthn") {
+ return true;
+ }
+
+ event.preventDefault();
+
+ try {
+ const createOptionsRequest = await fetch(data.challengeUrl as string);
+ const createOptions = await createOptionsRequest.text();
+
+ const options = WebAuthnJSON.parseCreationOptionsFromJSON({
+ publicKey: JSON.parse(createOptions),
+ });
+
+ const credential = await WebAuthnJSON.create(options);
+
+ if (credential) {
+ this.webauthnCredentialTarget.value = JSON.stringify(credential);
+ const form = event.target as HTMLFormElement;
+ form.submit();
+ }
+
+ return true;
+ } catch (error) {
+ console.log(`Error registering device: ${error}`);
+ return false;
+ }
+ }
+
+ qrCodeElementTargetConnected(target: HTMLElement) {
QrCreator.render(
{
text: target.dataset.value as string,
radius: 0,
- ecLevel: 'H',
- fill: '#222222',
- background: '#FFFFFF',
+ ecLevel: "H",
+ fill: "#222222",
+ background: "#FFFFFF",
size: 250,
},
- target,
+ target
);
}
- print(evt:MouseEvent) {
+ print(evt: MouseEvent) {
evt.preventDefault();
window.print();
}
- toggleResendOptions(evt:MouseEvent) {
+ toggleResendOptions(evt: MouseEvent) {
evt.preventDefault();
this.resendOptionsTarget.hidden = !this.resendOptionsTarget.hidden;
}
diff --git a/modules/two_factor_authentication/app/controllers/two_factor_authentication/base_controller.rb b/modules/two_factor_authentication/app/controllers/two_factor_authentication/base_controller.rb
index 0e8c5b53ae5..fe7f6bb0f71 100644
--- a/modules/two_factor_authentication/app/controllers/two_factor_authentication/base_controller.rb
+++ b/modules/two_factor_authentication/app/controllers/two_factor_authentication/base_controller.rb
@@ -14,6 +14,7 @@ module ::TwoFactorAuthentication
if params[:type]
@device_type = params[:type].to_sym
@device = new_device_type! @device_type
+
render 'two_factor_authentication/two_factor_devices/new'
else
@available_devices = available_devices
@@ -67,6 +68,17 @@ module ::TwoFactorAuthentication
end
end
+ def webauthn_challenge
+ device = new_device_type!(:webauthn)
+
+ ensure_user_has_webauthn_id!
+
+ webauthn_options = device.options_for_create
+ session[:webauthn_challenge] = webauthn_options.challenge
+
+ render json: webauthn_options
+ end
+
private
##
@@ -151,6 +163,34 @@ module ::TwoFactorAuthentication
)
end
+ def new_webauthn_device_params
+ permitted_device_params.merge(
+ user: target_user,
+ default: false,
+ active: true,
+ webauthn_external_id: webauthn_credential.id,
+ webauthn_public_key: webauthn_credential.public_key,
+ webauthn_sign_count: webauthn_credential.sign_count
+ )
+ end
+
+ def webauthn_credential
+ @webauthn_credential ||= WebAuthn::Credential.from_create(JSON.parse(params[:device][:webauthn_credential]))
+ end
+
+ def assign_webauthn_attributes
+ @device.assign_attributes
+ end
+
+ def verify_webauthn_credential
+ webauthn_credential.verify(session[:webauthn_challenge])
+ session.delete(:webauthn_challenge)
+ true
+ rescue WebAuthn::Error => e
+ Rails.logger.error "Failed to verify WebAuthn credential for registration. #{e}"
+ false
+ end
+
def logout_other_sessions
if current_user == target_user
Rails.logger.info { "First 2FA device registered for #{target_user}, terminating other logged in sessions." }
@@ -219,5 +259,11 @@ module ::TwoFactorAuthentication
def token_service(device)
::TwoFactorAuthentication::TokenService.new user: target_user, use_device: device
end
+
+ def ensure_user_has_webauthn_id!
+ return if target_user.webauthn_id
+
+ target_user.update(webauthn_id: WebAuthn.generate_user_id)
+ end
end
end
diff --git a/modules/two_factor_authentication/app/controllers/two_factor_authentication/my/two_factor_devices_controller.rb b/modules/two_factor_authentication/app/controllers/two_factor_authentication/my/two_factor_devices_controller.rb
index e3aac29957e..fa9b5fce63c 100644
--- a/modules/two_factor_authentication/app/controllers/two_factor_authentication/my/two_factor_devices_controller.rb
+++ b/modules/two_factor_authentication/app/controllers/two_factor_authentication/my/two_factor_devices_controller.rb
@@ -6,7 +6,7 @@ module ::TwoFactorAuthentication
before_action :set_user_variables
- before_action :find_device, except: %i[new index register]
+ before_action :find_device, except: %i[new index register webauthn_challenge]
# Remember token functionality
include ::TwoFactorAuthentication::RememberToken
@@ -34,10 +34,20 @@ module ::TwoFactorAuthentication
@device_type = params[:key].to_sym
@device = new_device_type! @device_type
- @device.attributes = new_device_params
+ success_target_action = :confirm
+
+ if @device_type == :webauthn
+ if verify_webauthn_credential
+ @device.attributes = new_webauthn_device_params
+ success_target_action = :index
+ end
+ else
+ @device.attributes = new_device_params
+ end
+
if @device.save
Rails.logger.info "User ##{current_user.id} registered a new (unconfirmed) device #{@device_type}."
- redirect_to action: :confirm, device_id: @device.id
+ redirect_to action: success_target_action, device_id: @device.id
else
Rails.logger.warn { "User ##{current_user.id} failed to register a device #{@device_type}." }
render 'two_factor_authentication/two_factor_devices/new'
diff --git a/modules/two_factor_authentication/app/models/two_factor_authentication/device/webauthn.rb b/modules/two_factor_authentication/app/models/two_factor_authentication/device/webauthn.rb
index a7f51cf9e7e..eca00e0dad7 100644
--- a/modules/two_factor_authentication/app/models/two_factor_authentication/device/webauthn.rb
+++ b/modules/two_factor_authentication/app/models/two_factor_authentication/device/webauthn.rb
@@ -17,5 +17,12 @@ module TwoFactorAuthentication
self.channel ||= :webauthn
end
validates_inclusion_of :channel, in: supported_channels
+
+ def options_for_create
+ @options_for_create ||= WebAuthn::Credential.options_for_create(
+ user: { id: user.webauthn_id, name: user.name },
+ exclude: TwoFactorAuthentication::Device::Webauthn.where(user:).pluck(:webauthn_external_id)
+ )
+ end
end
end
diff --git a/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/new.html.erb b/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/new.html.erb
index d10a1152022..2a4ac4a4796 100644
--- a/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/new.html.erb
+++ b/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/new.html.erb
@@ -1,17 +1,19 @@
<% html_title(t(:label_my_account), t('two_factor_authentication.devices.add_new')) -%>
<% breadcrumb_paths link_to(t('two_factor_authentication.label_two_factor_authentication'), index_path),
t('two_factor_authentication.devices.add_new') -%>
-
<%= toolbar title: t('two_factor_authentication.devices.add_new') %>
-
<%= labelled_tabular_form_for @device,
url: { action: :register },
- html: { class: nil, autocomplete: 'off' },
+ html: { class: nil, autocomplete: 'off', data: {
+ controller: "two-factor-authentication",
+ application_target: "dynamic",
+ challenge_url: url_for(action: :webauthn_challenge, format: :json),
+ device_type: @device_type,
+ action: "submit->two-factor-authentication#onCreateDevice"
+ } },
as: :device do |f| %>
-
<%= hidden_field_tag 'key', @device_type %>
<%= render partial: "two_factor_authentication/two_factor_devices/form", locals: { f: f, device_type: @device_type, device: @device, user: @user } %>
-
<p>
<%= styled_button_tag t(:button_continue), class: '-highlight -with-icon icon-checkmark' %>
<%= link_to t(:button_cancel), index_path, class: 'button -with-icon icon-cancel' %>
diff --git a/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/webauthn/_form.html.erb b/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/webauthn/_form.html.erb
new file mode 100644
index 00000000000..d687433ce85
--- /dev/null
+++ b/modules/two_factor_authentication/app/views/two_factor_authentication/two_factor_devices/webauthn/_form.html.erb
@@ -0,0 +1,11 @@
+<fieldset class="form--fieldset">
+ <legend class="form--fieldset-legend" title="<%= @device.name %>"><%= @device.name %></legend>
+ <p><%= t('two_factor_authentication.devices.webauthn.description') %></p>
+ <div class="form--field -required">
+ <%= f.text_field :identifier, required: true, container_class: '-middle' %>
+ <%= f.hidden_field :webauthn_credential, value: "", "data-two-factor-authentication-target": "webauthnCredential" %>
+ <div class="form--field-instructions">
+ <%= t('two_factor_authentication.devices.text_identifier') %>
+ </div>
+ </div>
+</fieldset>
diff --git a/modules/two_factor_authentication/config/routes.rb b/modules/two_factor_authentication/config/routes.rb
index ee878f269ea..eb927f54762 100644
--- a/modules/two_factor_authentication/config/routes.rb
+++ b/modules/two_factor_authentication/config/routes.rb
@@ -34,6 +34,9 @@ Rails.application.routes.draw do
# Make default
post :make_default, on: :member
+
+ # Request a challenge for WebAuthn
+ get :webauthn_challenge, on: :collection
end
end
end
@@ -63,6 +66,9 @@ Rails.application.routes.draw do
# Make a device a default
post :make_default, on: :member
+
+ # Request a challenge for WebAuthn
+ get :webauthn_challenge, on: :collection
end
end
end
diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb
index 6b7a9cfc16b..26e8ab7c8ff 100644
--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb
+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb
@@ -61,6 +61,11 @@ module OpenProject::TwoFactorAuthentication
}) do
two_factor_authentication_request_path
end
+
+ WebAuthn.configure do |config|
+ config.origin = "http://localhost:3000"
+ config.rp_name = "Example Inc."
+ end
end
end
end