Module: BetterAuth::Plugins
- Defined in:
- lib/better_auth/plugins/oauth_provider.rb
Defined Under Namespace
Modules: OAuthProvider
Class Method Summary collapse
- .oauth_admin_create_client_endpoint(config) ⇒ Object
- .oauth_admin_update_client_endpoint(_config) ⇒ Object
- .oauth_assert_client_privilege!(ctx, config, session, action) ⇒ Object
- .oauth_assert_owned_client!(client, session, config = nil) ⇒ Object
- .oauth_authorization_redirect(ctx, config, query, session, client, scopes) ⇒ Object
- .oauth_authorize_endpoint(config) ⇒ Object
- .oauth_authorize_error_redirect(ctx, query, error, description) ⇒ Object
- .oauth_authorize_flow(ctx, config, query, continue_post_login: false) ⇒ Object
- .oauth_client_update_data(source, admin: false) ⇒ Object
- .oauth_consent_endpoint(config) ⇒ Object
- .oauth_consent_granted?(ctx, client_id, user_id, scopes) ⇒ Boolean
- .oauth_consent_response(consent) ⇒ Object
- .oauth_continue_endpoint(config) ⇒ Object
- .oauth_create_client_endpoint(config) ⇒ Object
- .oauth_delete_client_endpoint(config) ⇒ Object
- .oauth_delete_consent_endpoint ⇒ Object
- .oauth_delete_prompt!(query, prompt) ⇒ Object
- .oauth_end_session_endpoint ⇒ Object
- .oauth_find_user_consent(ctx, session, client_id) ⇒ Object
- .oauth_get_client_endpoint(config) ⇒ Object
- .oauth_get_client_public_endpoint(_config) ⇒ Object
- .oauth_get_client_public_prelogin_endpoint(_config) ⇒ Object
- .oauth_get_consent_endpoint ⇒ Object
- .oauth_id_token_signing_algs(ctx, config) ⇒ Object
- .oauth_introspect_endpoint(config) ⇒ Object
- .oauth_introspect_jwt_access_token(ctx, client, token) ⇒ Object
- .oauth_jwks_uri(config) ⇒ Object
- .oauth_jwt_access_token?(config, audience) ⇒ Boolean
- .oauth_legacy_delete_client_endpoint(config) ⇒ Object
- .oauth_legacy_delete_consent_endpoint ⇒ Object
- .oauth_legacy_get_client_endpoint(config) ⇒ Object
- .oauth_legacy_get_client_public_endpoint(_config) ⇒ Object
- .oauth_legacy_get_consent_endpoint ⇒ Object
- .oauth_legacy_list_clients_endpoint(config) ⇒ Object
- .oauth_legacy_list_consents_endpoint ⇒ Object
- .oauth_legacy_update_client_endpoint(config) ⇒ Object
- .oauth_legacy_update_consent_endpoint ⇒ Object
- .oauth_list_clients_endpoint(config) ⇒ Object
- .oauth_list_consents_endpoint ⇒ Object
- .oauth_metadata_headers ⇒ Object
- .oauth_openid_metadata_endpoint(config) ⇒ Object
- .oauth_prompt_page(config, type) ⇒ Object
- .oauth_prompt_redirect(ctx, config, query, type, page: nil) ⇒ Object
- .oauth_prompt_values ⇒ Object
- .oauth_provider(options = {}) ⇒ Object
- .oauth_provider_endpoints(config) ⇒ Object
- .oauth_provider_rate_limits(config) ⇒ Object
- .oauth_provider_schema ⇒ Object
- .oauth_public_client_response(client) ⇒ Object
- .oauth_rate_limit_rule(rate_limit, key, path, window:, max:) ⇒ Object
- .oauth_redirect_location ⇒ Object
- .oauth_redirect_with_code(ctx, config, query, session, client, scopes) ⇒ Object
- .oauth_register_client_endpoint(config) ⇒ Object
- .oauth_revoke_endpoint(config) ⇒ Object
- .oauth_rotate_client_secret_endpoint(config) ⇒ Object
- .oauth_server_metadata_endpoint(config) ⇒ Object
- .oauth_signed_query(ctx, query) ⇒ Object
- .oauth_store_consent(ctx, client, session, scopes) ⇒ Object
- .oauth_token_auth_methods(config) ⇒ Object
- .oauth_token_endpoint(config) ⇒ Object
- .oauth_update_client_endpoint(config) ⇒ Object
- .oauth_update_consent_endpoint ⇒ Object
- .oauth_userinfo_endpoint(config) ⇒ Object
- .oauth_validate_resource!(ctx, config, body) ⇒ Object
- .oauth_verified_query!(ctx, oauth_query) ⇒ Object
Class Method Details
.oauth_admin_create_client_endpoint(config) ⇒ Object
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 291 def oauth_admin_create_client_endpoint(config) Endpoint.new(path: "/admin/oauth2/create-client", method: "POST", metadata: {server_only: true}) do |ctx| body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.create_client( ctx, model: "oauthClient", body: body, owner_session: nil, default_scopes: config[:client_registration_default_scopes] || config[:scopes], allowed_scopes: config[:client_registration_allowed_scopes] || config[:scopes], store_client_secret: config[:store_client_secret], prefix: config[:prefix], dynamic_registration: false, admin: true ) ctx.json(client, status: 201, headers: {"Cache-Control" => "no-store", "Pragma" => "no-cache"}) end end |
.oauth_admin_update_client_endpoint(_config) ⇒ Object
310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 310 def oauth_admin_update_client_endpoint(_config) Endpoint.new(path: "/admin/oauth2/update-client", method: "PATCH", metadata: {server_only: true}) do |ctx| body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client update = oauth_client_update_data(OAuthProtocol.stringify_keys(body["update"] || {}), admin: true) updated = update.empty? ? client : ctx.context.adapter.update(model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}], update: update.merge(updatedAt: Time.now)) ctx.json(OAuthProtocol.client_response(updated, include_secret: false)) end end |
.oauth_assert_client_privilege!(ctx, config, session, action) ⇒ Object
849 850 851 852 853 854 855 856 857 858 859 860 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 849 def oauth_assert_client_privilege!(ctx, config, session, action) callback = config[:client_privileges] return unless callback.respond_to?(:call) allowed = callback.call({ headers: ctx.headers, action: action, session: session[:session], user: session[:user] }) raise APIError.new("UNAUTHORIZED") unless allowed end |
.oauth_assert_owned_client!(client, session, config = nil) ⇒ Object
837 838 839 840 841 842 843 844 845 846 847 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 837 def oauth_assert_owned_client!(client, session, config = nil) data = OAuthProtocol.stringify_keys(client) return if data["userId"] && data["userId"] == session[:user]["id"] if data["referenceId"] && config && config[:client_reference].respond_to?(:call) reference_id = config[:client_reference].call({user: session[:user], session: session[:session]}) return if data["referenceId"] == reference_id end raise APIError.new("NOT_FOUND", message: "client not found") end |
.oauth_authorization_redirect(ctx, config, query, session, client, scopes) ⇒ Object
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 677 def (ctx, config, query, session, client, scopes) code = Crypto.random_string(32) OAuthProtocol.store_code( config[:store], code: code, client_id: query["client_id"], redirect_uri: query["redirect_uri"], session: session, scopes: scopes, code_challenge: query["code_challenge"], code_challenge_method: query["code_challenge_method"], nonce: query["nonce"], reference_id: OAuthProtocol.stringify_keys(client)["referenceId"] ) OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], code: code, state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx))) end |
.oauth_authorize_endpoint(config) ⇒ Object
419 420 421 422 423 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 419 def (config) Endpoint.new(path: "/oauth2/authorize", method: "GET") do |ctx| (ctx, config, OAuthProtocol.stringify_keys(ctx.query)) end end |
.oauth_authorize_error_redirect(ctx, query, error, description) ⇒ Object
806 807 808 809 810 811 812 813 814 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 806 def (ctx, query, error, description) OAuthProtocol.redirect_uri_with_params( query["redirect_uri"], error: error, error_description: description, state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)) ) end |
.oauth_authorize_flow(ctx, config, query, continue_post_login: false) ⇒ Object
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 445 def (ctx, config, query, continue_post_login: false) response_type = query["response_type"].to_s client = OAuthProtocol.find_client(ctx, "oauthClient", query["client_id"]) raise APIError.new("BAD_REQUEST", message: "invalid_client") unless client OAuthProtocol.validate_redirect_uri!(client, query["redirect_uri"]) if response_type != "code" raise ctx.redirect((ctx, query, "unsupported_response_type", "response_type must be code")) end scopes = OAuthProtocol.parse_scopes(query["scope"]) scopes = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(client)["scopes"] || config[:scopes]) if scopes.empty? prompts = OAuthProtocol.parse_scopes(query["prompt"]) client_data = OAuthProtocol.stringify_keys(client) if client_data["disabled"] raise ctx.redirect((ctx, query, "invalid_client", "client is disabled")) end allowed_scopes = OAuthProtocol.parse_scopes(client_data["scopes"]) allowed_scopes = OAuthProtocol.parse_scopes(config[:scopes]) if allowed_scopes.empty? unless scopes.all? { |scope| allowed_scopes.include?(scope) } raise ctx.redirect((ctx, query, "invalid_scope", "invalid scope")) end pkce_error = OAuthProtocol.(client_data, scopes, query["code_challenge"], query["code_challenge_method"]) raise ctx.redirect((ctx, query, "invalid_request", pkce_error)) if pkce_error session = Routes.current_session(ctx, allow_nil: true) unless session if prompts.include?("none") raise ctx.redirect(OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], error: "login_required", state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)))) end if prompts.include?("create") raise ctx.redirect(oauth_prompt_redirect(ctx, config, query, "create")) end raise ctx.redirect(oauth_prompt_redirect(ctx, config, query, "login")) end if prompts.include?("select_account") && !continue_post_login if prompts.include?("none") raise ctx.redirect(OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], error: "account_selection_required", state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)))) end raise ctx.redirect(oauth_prompt_redirect(ctx, config, query, "select_account")) end if config.dig(:post_login, :should_redirect).respond_to?(:call) && !continue_post_login should_redirect = config.dig(:post_login, :should_redirect).call({user: session[:user], session: session[:session], client: client_data, scopes: scopes}) if should_redirect if prompts.include?("none") raise ctx.redirect(OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], error: "interaction_required", state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)))) end raise ctx.redirect(oauth_prompt_redirect(ctx, config, query, "post_login", page: should_redirect.is_a?(String) ? should_redirect : nil)) end end = !client_data["skipConsent"] && (prompts.include?("consent") || !(ctx, client_data["clientId"], session[:user]["id"], scopes)) if if prompts.include?("none") raise ctx.redirect(OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], error: "consent_required", state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)))) end = Crypto.random_string(32) config[:store][:consents][] = { query: query, session: session, client: client, scopes: scopes, expires_at: Time.now + 600 } raise ctx.redirect(OAuthProtocol.redirect_uri_with_params(config[:consent_page], consent_code: , client_id: client_data["clientId"], scope: OAuthProtocol.scope_string(scopes))) end oauth_redirect_with_code(ctx, config, query, session, client, scopes) end |
.oauth_client_update_data(source, admin: false) ⇒ Object
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 862 def oauth_client_update_data(source, admin: false) update = {} update["name"] = source["client_name"] || source["name"] if source.key?("client_name") || source.key?("name") update["uri"] = source["client_uri"] if source.key?("client_uri") update["icon"] = source["logo_uri"] if source.key?("logo_uri") if source.key?("redirect_uris") redirects = Array(source["redirect_uris"]).map(&:to_s) update["redirectUris"] = redirects update["redirectUrls"] = redirects.join(",") end update["postLogoutRedirectUris"] = Array(source["post_logout_redirect_uris"]).map(&:to_s) if source.key?("post_logout_redirect_uris") update["grantTypes"] = Array(source["grant_types"]).map(&:to_s) if source.key?("grant_types") update["responseTypes"] = Array(source["response_types"]).map(&:to_s) if source.key?("response_types") update["scopes"] = OAuthProtocol.parse_scopes(source["scope"] || source["scopes"]) if source.key?("scope") || source.key?("scopes") update["enableEndSession"] = !!(source["enable_end_session"] || source["enableEndSession"]) if source.key?("enable_end_session") || source.key?("enableEndSession") update["skipConsent"] = !!(source["skip_consent"] || source["skipConsent"]) if admin && (source.key?("skip_consent") || source.key?("skipConsent")) update["clientSecretExpiresAt"] = source["client_secret_expires_at"] if admin && source.key?("client_secret_expires_at") update["subjectType"] = source["subject_type"] || source["subjectType"] if admin && (source.key?("subject_type") || source.key?("subjectType")) update["metadata"] = source["metadata"] if source.key?("metadata") update end |
.oauth_consent_endpoint(config) ⇒ Object
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 594 def (config) Endpoint.new(path: "/oauth2/consent", method: "POST") do |ctx| Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) = config[:store][:consents].delete(body["consent_code"].to_s) raise APIError.new("BAD_REQUEST", message: "invalid consent_code") unless raise APIError.new("BAD_REQUEST", message: "expired consent_code") if [:expires_at] <= Time.now query = [:query] if body["accept"] == false || body["accept"].to_s == "false" redirect = OAuthProtocol.redirect_uri_with_params(query["redirect_uri"], error: "access_denied", state: query["state"], iss: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx))) next ctx.json({redirectURI: redirect}) end granted_scopes = OAuthProtocol.parse_scopes(body["scope"] || body["scopes"]) granted_scopes = [:scopes] if granted_scopes.empty? unless granted_scopes.all? { |scope| [:scopes].include?(scope) } raise APIError.new("BAD_REQUEST", message: "invalid_scope") end (ctx, [:client], [:session], granted_scopes) redirect = (ctx, config, query, [:session], [:client], granted_scopes) ctx.json({redirectURI: redirect}) end end |
.oauth_consent_granted?(ctx, client_id, user_id, scopes) ⇒ Boolean
698 699 700 701 702 703 704 705 706 707 708 709 710 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 698 def (ctx, client_id, user_id, scopes) = ctx.context.adapter.find_one( model: "oauthConsent", where: [ {field: "clientId", value: client_id}, {field: "userId", value: user_id} ] ) return false unless granted = OAuthProtocol.parse_scopes(["scopes"]) scopes.all? { |scope| granted.include?(scope) } end |
.oauth_consent_response(consent) ⇒ Object
894 895 896 897 898 899 900 901 902 903 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 894 def () data = OAuthProtocol.stringify_keys() { id: data["id"], client_id: data["clientId"], user_id: data["userId"], scope: OAuthProtocol.scope_string(data["scopes"]), scopes: OAuthProtocol.parse_scopes(data["scopes"]) }.compact end |
.oauth_continue_endpoint(config) ⇒ Object
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 425 def oauth_continue_endpoint(config) Endpoint.new(path: "/oauth2/continue", method: "POST") do |ctx| Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) action = if body["selected"] == true "select_account" elsif body["created"] == true "create" elsif body["postLogin"] == true || body["post_login"] == true "post_login" end raise APIError.new("BAD_REQUEST", message: "Missing parameters") unless action query = oauth_verified_query!(ctx, body["oauth_query"]) oauth_delete_prompt!(query, action) unless action == "post_login" url = oauth_redirect_location { (ctx, config, query, continue_post_login: action == "post_login") } ctx.json({redirect: true, url: url}) end end |
.oauth_create_client_endpoint(config) ⇒ Object
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 191 def oauth_create_client_endpoint(config) Endpoint.new(path: "/oauth2/create-client", method: "POST") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "create") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.create_client( ctx, model: "oauthClient", body: body, owner_session: session, default_scopes: config[:client_registration_default_scopes] || config[:scopes], allowed_scopes: config[:client_registration_allowed_scopes] || config[:scopes], store_client_secret: config[:store_client_secret], prefix: config[:prefix], dynamic_registration: false, admin: false ) ctx.json(client, status: 201, headers: {"Cache-Control" => "no-store", "Pragma" => "no-cache"}) end end |
.oauth_delete_client_endpoint(config) ⇒ Object
262 263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 262 def oauth_delete_client_endpoint(config) Endpoint.new(path: "/oauth2/delete-client", method: "POST") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "delete") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) ctx.context.adapter.delete(model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}]) ctx.json({deleted: true}) end end |
.oauth_delete_consent_endpoint ⇒ Object
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 400 def Endpoint.new(path: "/oauth2/delete-consent", method: "POST") do |ctx| session = Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) id = body["id"] = if id.to_s.empty? (ctx, session, body["client_id"]) else ctx.context.adapter.find_one(model: "oauthConsent", where: [{field: "id", value: id}]) end raise APIError.new("NOT_FOUND", message: "missing id") if id.to_s.empty? && body["client_id"].to_s.empty? raise APIError.new("NOT_FOUND", message: "consent not found") unless raise APIError.new("UNAUTHORIZED") unless OAuthProtocol.stringify_keys()["userId"] == session[:user]["id"] ctx.context.adapter.delete(model: "oauthConsent", where: [{field: "id", value: OAuthProtocol.stringify_keys()["id"]}]) ctx.json({deleted: true}) end end |
.oauth_delete_prompt!(query, prompt) ⇒ Object
575 576 577 578 579 580 581 582 583 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 575 def oauth_delete_prompt!(query, prompt) prompts = OAuthProtocol.parse_scopes(query["prompt"]) prompts.delete(prompt) if prompts.empty? query.delete("prompt") else query["prompt"] = OAuthProtocol.scope_string(prompts) end end |
.oauth_end_session_endpoint ⇒ Object
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 768 def oauth_end_session_endpoint Endpoint.new(path: "/oauth2/end-session", method: ["GET", "POST"], metadata: {allowed_media_types: ["application/x-www-form-urlencoded", "application/json"]}) do |ctx| input = OAuthProtocol.stringify_keys((ctx.method == "GET") ? ctx.query : ctx.body) id_token_hint = input["id_token_hint"].to_s raise APIError.new("UNAUTHORIZED", message: "invalid id token") if id_token_hint.empty? decoded = ::JWT.decode(id_token_hint, nil, false).first client_id = input["client_id"] || decoded["aud"] client = OAuthProtocol.find_client(ctx, "oauthClient", client_id) raise APIError.new("BAD_REQUEST", message: "invalid_client") unless client client_data = OAuthProtocol.stringify_keys(client) raise APIError.new("BAD_REQUEST", message: "invalid_client") if client_data["disabled"] raise APIError.new("UNAUTHORIZED", message: "client unable to logout") unless client_data["enableEndSession"] payload = Crypto.verify_jwt(id_token_hint, client_data["clientId"]) raise APIError.new("UNAUTHORIZED", message: "invalid id token") unless payload raise APIError.new("BAD_REQUEST", message: "audience mismatch") if input["client_id"] && payload["aud"] != input["client_id"] if payload["sid"] ctx.context.adapter.delete(model: "session", where: [{field: "id", value: payload["sid"]}]) end if input["post_logout_redirect_uri"] unless OAuthProtocol.client_logout_redirect_uris(client_data).include?(input["post_logout_redirect_uri"]) raise APIError.new("BAD_REQUEST", message: "invalid post_logout_redirect_uri") end redirect = OAuthProtocol.redirect_uri_with_params(input["post_logout_redirect_uri"], state: input["state"]) raise ctx.redirect(redirect) end ctx.json({status: true}) rescue ::JWT::DecodeError raise APIError.new("UNAUTHORIZED", message: "invalid id token") end end |
.oauth_find_user_consent(ctx, session, client_id) ⇒ Object
884 885 886 887 888 889 890 891 892 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 884 def (ctx, session, client_id) ctx.context.adapter.find_one( model: "oauthConsent", where: [ {field: "clientId", value: client_id}, {field: "userId", value: session[:user]["id"]} ] ) end |
.oauth_get_client_endpoint(config) ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 212 def oauth_get_client_endpoint(config) Endpoint.new(path: "/oauth2/get-client", method: "GET") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "read") query = OAuthProtocol.stringify_keys(ctx.query) client = OAuthProtocol.find_client(ctx, "oauthClient", query["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) ctx.json(OAuthProtocol.client_response(client, include_secret: false)) end end |
.oauth_get_client_public_endpoint(_config) ⇒ Object
225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 225 def oauth_get_client_public_endpoint(_config) Endpoint.new(path: "/oauth2/public-client", method: "GET") do |ctx| Routes.current_session(ctx, allow_nil: true) query = OAuthProtocol.stringify_keys(ctx.query) client = OAuthProtocol.find_client(ctx, "oauthClient", query["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client raise APIError.new("NOT_FOUND", message: "client not found") if OAuthProtocol.stringify_keys(client)["disabled"] ctx.json(oauth_public_client_response(client)) end end |
.oauth_get_client_public_prelogin_endpoint(_config) ⇒ Object
237 238 239 240 241 242 243 244 245 246 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 237 def oauth_get_client_public_prelogin_endpoint(_config) Endpoint.new(path: "/oauth2/public-client-prelogin", method: "POST") do |ctx| input = OAuthProtocol.stringify_keys(ctx.body).merge(OAuthProtocol.stringify_keys(ctx.query)) client = OAuthProtocol.find_client(ctx, "oauthClient", input["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client raise APIError.new("NOT_FOUND", message: "client not found") if OAuthProtocol.stringify_keys(client)["disabled"] ctx.json(oauth_public_client_response(client)) end end |
.oauth_get_consent_endpoint ⇒ Object
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 352 def Endpoint.new(path: "/oauth2/get-consent", method: "GET") do |ctx| session = Routes.current_session(ctx) query = OAuthProtocol.stringify_keys(ctx.query) = if query["id"].to_s.empty? (ctx, session, query["client_id"]) else ctx.context.adapter.find_one(model: "oauthConsent", where: [{field: "id", value: query["id"]}]) end raise APIError.new("NOT_FOUND", message: "missing id") unless query["id"] || query["client_id"] raise APIError.new("NOT_FOUND", message: "consent not found") unless raise APIError.new("UNAUTHORIZED") unless OAuthProtocol.stringify_keys()["userId"] == session[:user]["id"] ctx.json(()) end end |
.oauth_id_token_signing_algs(ctx, config) ⇒ Object
934 935 936 937 938 939 940 941 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 934 def oauth_id_token_signing_algs(ctx, config) return ["HS256"] if config[:disable_jwt_plugin] jwt_plugin = ctx.context..plugins.find { |plugin| plugin.id == "jwt" } alg = config.dig(:jwt, :jwks, :key_pair_config, :alg) || jwt_plugin&.&.dig(:jwks, :key_pair_config, :alg) alg ? [alg] : ["EdDSA"] end |
.oauth_introspect_endpoint(config) ⇒ Object
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 730 def oauth_introspect_endpoint(config) Endpoint.new(path: "/oauth2/introspect", method: "POST", metadata: {allowed_media_types: ["application/x-www-form-urlencoded", "application/json"]}) do |ctx| client = OAuthProtocol.authenticate_client!(ctx, "oauthClient", store_client_secret: config[:store_client_secret], prefix: config[:prefix]) body = OAuthProtocol.stringify_keys(ctx.body) token = OAuthProtocol.find_token_by_hint(config[:store], body["token"].to_s, body["token_type_hint"], prefix: config[:prefix]) active = token && !token["revoked"] && (!token["expiresAt"] || token["expiresAt"] > Time.now) if active next ctx.json({ active: true, client_id: token["clientId"], scope: OAuthProtocol.scope_string(token["scope"] || token["scopes"]), sub: token.dig("user", "id"), exp: token["expiresAt"]&.to_i }) end jwt = oauth_introspect_jwt_access_token(ctx, client, body["token"].to_s) ctx.json(jwt || {active: false}) end end |
.oauth_introspect_jwt_access_token(ctx, client, token) ⇒ Object
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 820 def oauth_introspect_jwt_access_token(ctx, client, token) payload = ::JWT.decode(token, ctx.context.secret, true, algorithm: "HS256").first client_data = OAuthProtocol.stringify_keys(client) return nil unless payload["azp"] == client_data["clientId"] { active: true, client_id: payload["azp"], scope: payload["scope"], sub: payload["sub"], aud: payload["aud"], exp: payload["exp"] }.compact rescue ::JWT::DecodeError nil end |
.oauth_jwks_uri(config) ⇒ Object
922 923 924 925 926 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 922 def oauth_jwks_uri(config) config.dig(:advertised_metadata, :jwks_uri) || config[:jwks_uri] || config.dig(:jwks, :remote_url) end |
.oauth_jwt_access_token?(config, audience) ⇒ Boolean
816 817 818 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 816 def oauth_jwt_access_token?(config, audience) !!audience && !config[:disable_jwt_plugin] && !config[:disable_jwt_access_tokens] end |
.oauth_legacy_delete_client_endpoint(config) ⇒ Object
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1003 def oauth_legacy_delete_client_endpoint(config) Endpoint.new(path: "/oauth2/client", method: "DELETE") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "delete") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) ctx.context.adapter.delete(model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}]) ctx.json({deleted: true}) end end |
.oauth_legacy_delete_consent_endpoint ⇒ Object
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1053 def Endpoint.new(path: "/oauth2/consent", method: "DELETE") do |ctx| session = Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) = (ctx, session, body["client_id"]) raise APIError.new("NOT_FOUND", message: "consent not found") unless ctx.context.adapter.delete(model: "oauthConsent", where: [{field: "id", value: OAuthProtocol.stringify_keys()["id"]}]) ctx.json({deleted: true}) end end |
.oauth_legacy_get_client_endpoint(config) ⇒ Object
960 961 962 963 964 965 966 967 968 969 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 960 def oauth_legacy_get_client_endpoint(config) Endpoint.new(path: "/oauth2/client/:id", method: "GET") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "read") client = OAuthProtocol.find_client(ctx, "oauthClient", ctx.params["id"] || ctx.params[:id]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) ctx.json(OAuthProtocol.client_response(client, include_secret: false)) end end |
.oauth_legacy_get_client_public_endpoint(_config) ⇒ Object
971 972 973 974 975 976 977 978 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 971 def oauth_legacy_get_client_public_endpoint(_config) Endpoint.new(path: "/oauth2/client", method: "GET") do |ctx| query = OAuthProtocol.stringify_keys(ctx.query) client = OAuthProtocol.find_client(ctx, "oauthClient", query["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client ctx.json(OAuthProtocol.client_response(client, include_secret: false)) end end |
.oauth_legacy_get_consent_endpoint ⇒ Object
1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1024 def Endpoint.new(path: "/oauth2/consent", method: "GET") do |ctx| session = Routes.current_session(ctx) query = OAuthProtocol.stringify_keys(ctx.query) = (ctx, session, query["client_id"]) raise APIError.new("NOT_FOUND", message: "consent not found") unless ctx.json(()) end end |
.oauth_legacy_list_clients_endpoint(config) ⇒ Object
980 981 982 983 984 985 986 987 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 980 def oauth_legacy_list_clients_endpoint(config) Endpoint.new(path: "/oauth2/clients", method: "GET") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "list") clients = ctx.context.adapter.find_many(model: "oauthClient", where: [{field: "userId", value: session[:user]["id"]}]) ctx.json(clients.map { |client| OAuthProtocol.client_response(client, include_secret: false) }) end end |
.oauth_legacy_list_consents_endpoint ⇒ Object
1016 1017 1018 1019 1020 1021 1022 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1016 def Endpoint.new(path: "/oauth2/consents", method: "GET") do |ctx| session = Routes.current_session(ctx) = ctx.context.adapter.find_many(model: "oauthConsent", where: [{field: "userId", value: session[:user]["id"]}]) ctx.json(.map { || () }) end end |
.oauth_legacy_update_client_endpoint(config) ⇒ Object
989 990 991 992 993 994 995 996 997 998 999 1000 1001 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 989 def oauth_legacy_update_client_endpoint(config) Endpoint.new(path: "/oauth2/client", method: "PATCH") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "update") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) update = oauth_client_update_data(OAuthProtocol.stringify_keys(body["update"] || body)) updated = update.empty? ? client : ctx.context.adapter.update(model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}], update: update.merge(updatedAt: Time.now)) ctx.json(OAuthProtocol.client_response(updated, include_secret: false)) end end |
.oauth_legacy_update_consent_endpoint ⇒ Object
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1034 def Endpoint.new(path: "/oauth2/consent", method: "PATCH") do |ctx| session = Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) = (ctx, session, body["client_id"]) raise APIError.new("NOT_FOUND", message: "consent not found") unless scopes = OAuthProtocol.parse_scopes(body["scope"] || body["scopes"]) existing = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys()["scopes"]) raise APIError.new("BAD_REQUEST", message: "invalid_scope") unless scopes.all? { |scope| existing.include?(scope) } updated = ctx.context.adapter.update( model: "oauthConsent", where: [{field: "id", value: OAuthProtocol.stringify_keys()["id"]}], update: {scopes: scopes, updatedAt: Time.now} ) ctx.json((updated)) end end |
.oauth_list_clients_endpoint(config) ⇒ Object
248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 248 def oauth_list_clients_endpoint(config) Endpoint.new(path: "/oauth2/get-clients", method: "GET") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "list") reference_id = config[:client_reference]&.call({user: session[:user], session: session[:session]}) clients = if reference_id ctx.context.adapter.find_many(model: "oauthClient", where: [{field: "referenceId", value: reference_id}]) else ctx.context.adapter.find_many(model: "oauthClient", where: [{field: "userId", value: session[:user]["id"]}]) end ctx.json(clients.map { |client| OAuthProtocol.client_response(client, include_secret: false) }) end end |
.oauth_list_consents_endpoint ⇒ Object
344 345 346 347 348 349 350 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 344 def Endpoint.new(path: "/oauth2/get-consents", method: "GET") do |ctx| session = Routes.current_session(ctx) = ctx.context.adapter.find_many(model: "oauthConsent", where: [{field: "userId", value: session[:user]["id"]}]) ctx.json(.map { || () }) end end |
.oauth_metadata_headers ⇒ Object
918 919 920 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 918 def {"Cache-Control" => "public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"} end |
.oauth_openid_metadata_endpoint(config) ⇒ Object
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 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 124 def (config) Endpoint.new(path: "/.well-known/openid-configuration", method: "GET", metadata: {hide: true}) do |ctx| unless OAuthProtocol.parse_scopes(config[:scopes]).include?("openid") raise APIError.new("NOT_FOUND", message: "openid is not enabled") end base = OAuthProtocol.endpoint_base(ctx) = { issuer: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)), authorization_endpoint: "#{base}/oauth2/authorize", token_endpoint: "#{base}/oauth2/token", registration_endpoint: "#{base}/oauth2/register", introspection_endpoint: "#{base}/oauth2/introspect", revocation_endpoint: "#{base}/oauth2/revoke", response_types_supported: ["code"], response_modes_supported: ["query"], grant_types_supported: config[:grant_types], token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"], introspection_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], revocation_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], code_challenge_methods_supported: ["S256"], authorization_response_iss_parameter_supported: true, scopes_supported: config.dig(:advertised_metadata, :scopes_supported) || config[:scopes], userinfo_endpoint: "#{base}/oauth2/userinfo", subject_types_supported: config[:pairwise_secret] ? ["public", "pairwise"] : ["public"], id_token_signing_alg_values_supported: oauth_id_token_signing_algs(ctx, config), end_session_endpoint: "#{base}/oauth2/end-session", acr_values_supported: ["urn:mace:incommon:iap:bronze"], prompt_values_supported: oauth_prompt_values, claims_supported: config.dig(:advertised_metadata, :claims_supported) || config[:claims] || [] } [:jwks_uri] = oauth_jwks_uri(config) if oauth_jwks_uri(config) ctx.json(, headers: ) end end |
.oauth_prompt_page(config, type) ⇒ Object
529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 529 def oauth_prompt_page(config, type) case type when "create" config.dig(:signup, :page) || config[:login_page] when "select_account" config.dig(:select_account, :page) || config[:login_page] when "post_login" config.dig(:post_login, :page) || config[:login_page] when "consent" config[:consent_page] else config[:login_page] end end |
.oauth_prompt_redirect(ctx, config, query, type, page: nil) ⇒ Object
523 524 525 526 527 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 523 def oauth_prompt_redirect(ctx, config, query, type, page: nil) target = page || oauth_prompt_page(config, type) "#{target}?#{oauth_signed_query(ctx, query)}" end |
.oauth_prompt_values ⇒ Object
943 944 945 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 943 def oauth_prompt_values ["login", "consent", "create", "select_account", "none"] end |
.oauth_provider(options = {}) ⇒ Object
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 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 29 def oauth_provider( = {}) config = { login_page: "/login", consent_page: "/oauth2/consent", scopes: [], grant_types: [OAuthProtocol::AUTH_CODE_GRANT, OAuthProtocol::CLIENT_CREDENTIALS_GRANT, OAuthProtocol::REFRESH_GRANT], allow_dynamic_client_registration: false, allow_unauthenticated_client_registration: false, client_registration_default_scopes: nil, client_registration_allowed_scopes: nil, signup: {}, select_account: {}, post_login: {}, store_client_secret: "plain", prefix: {}, refresh_token_expires_in: 2_592_000, store: OAuthProtocol.stores }.merge(normalize_hash()) Plugin.new( id: "oauth-provider", version: BetterAuth::OAuthProvider::VERSION, endpoints: oauth_provider_endpoints(config), schema: oauth_provider_schema, rate_limit: oauth_provider_rate_limits(config), options: config ) end |
.oauth_provider_endpoints(config) ⇒ Object
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 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 58 def oauth_provider_endpoints(config) { get_o_auth_server_config: (config), get_open_id_config: (config), register_o_auth_client: oauth_register_client_endpoint(config), create_o_auth_client: oauth_create_client_endpoint(config), admin_create_o_auth_client: oauth_admin_create_client_endpoint(config), admin_update_o_auth_client: oauth_admin_update_client_endpoint(config), get_o_auth_client: oauth_get_client_endpoint(config), get_o_auth_client_public: oauth_get_client_public_endpoint(config), get_o_auth_client_public_prelogin: oauth_get_client_public_prelogin_endpoint(config), get_o_auth_clients: oauth_list_clients_endpoint(config), list_o_auth_clients: oauth_list_clients_endpoint(config), delete_o_auth_client: oauth_delete_client_endpoint(config), update_o_auth_client: oauth_update_client_endpoint(config), rotate_o_auth_client_secret: oauth_rotate_client_secret_endpoint(config), get_o_auth_consents: , list_o_auth_consents: , get_o_auth_consent: , update_o_auth_consent: , delete_o_auth_consent: , legacy_get_o_auth_client: oauth_legacy_get_client_endpoint(config), legacy_get_o_auth_client_public: oauth_legacy_get_client_public_endpoint(config), legacy_list_o_auth_clients: oauth_legacy_list_clients_endpoint(config), legacy_update_o_auth_client: oauth_legacy_update_client_endpoint(config), legacy_delete_o_auth_client: oauth_legacy_delete_client_endpoint(config), legacy_list_o_auth_consents: , legacy_get_o_auth_consent: , legacy_update_o_auth_consent: , legacy_delete_o_auth_consent: , o_auth2_authorize: (config), o_auth2_continue: oauth_continue_endpoint(config), o_auth2_consent: (config), o_auth2_token: oauth_token_endpoint(config), o_auth2_introspect: oauth_introspect_endpoint(config), o_auth2_revoke: oauth_revoke_endpoint(config), o_auth2_user_info: oauth_userinfo_endpoint(config), o_auth2_end_session: oauth_end_session_endpoint } end |
.oauth_provider_rate_limits(config) ⇒ Object
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1064 def oauth_provider_rate_limits(config) rate_limit = normalize_hash(config[:rate_limit] || {}) [ oauth_rate_limit_rule(rate_limit, :token, "/oauth2/token", window: 60, max: 20), oauth_rate_limit_rule(rate_limit, :authorize, "/oauth2/authorize", window: 60, max: 30), oauth_rate_limit_rule(rate_limit, :introspect, "/oauth2/introspect", window: 60, max: 100), oauth_rate_limit_rule(rate_limit, :revoke, "/oauth2/revoke", window: 60, max: 30), oauth_rate_limit_rule(rate_limit, :register, "/oauth2/register", window: 60, max: 5), oauth_rate_limit_rule(rate_limit, :userinfo, "/oauth2/userinfo", window: 60, max: 60) ].compact end |
.oauth_provider_schema ⇒ Object
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1088 def oauth_provider_schema { oauthClient: { modelName: "oauthClient", fields: { clientId: {type: "string", unique: true, required: true}, clientSecret: {type: "string", required: false}, disabled: {type: "boolean", default_value: false, required: false}, skipConsent: {type: "boolean", required: false}, enableEndSession: {type: "boolean", required: false}, clientSecretExpiresAt: {type: "number", required: false}, scopes: {type: "string[]", required: false}, userId: {type: "string", required: false}, createdAt: {type: "date", required: true, default_value: -> { Time.now }}, updatedAt: {type: "date", required: true, default_value: -> { Time.now }, on_update: -> { Time.now }}, name: {type: "string", required: false}, uri: {type: "string", required: false}, icon: {type: "string", required: false}, contacts: {type: "string[]", required: false}, tos: {type: "string", required: false}, policy: {type: "string", required: false}, softwareId: {type: "string", required: false}, softwareVersion: {type: "string", required: false}, softwareStatement: {type: "string", required: false}, redirectUris: {type: "string[]", required: true}, postLogoutRedirectUris: {type: "string[]", required: false}, tokenEndpointAuthMethod: {type: "string", required: false}, grantTypes: {type: "string[]", required: false}, responseTypes: {type: "string[]", required: false}, public: {type: "boolean", required: false}, type: {type: "string", required: false}, requirePKCE: {type: "boolean", required: false}, subjectType: {type: "string", required: false}, referenceId: {type: "string", required: false}, metadata: {type: "json", required: false} } }, oauthRefreshToken: { fields: { token: {type: "string", required: true}, clientId: {type: "string", required: true}, sessionId: {type: "string", required: false}, userId: {type: "string", required: false}, referenceId: {type: "string", required: false}, authTime: {type: "date", required: false}, expiresAt: {type: "date", required: false}, createdAt: {type: "date", required: true, default_value: -> { Time.now }}, revoked: {type: "date", required: false}, scopes: {type: "string[]", required: true} } }, oauthAccessToken: { modelName: "oauthAccessToken", fields: { token: {type: "string", unique: true, required: true}, expiresAt: {type: "date", required: true}, clientId: {type: "string", required: true}, userId: {type: "string", required: false}, sessionId: {type: "string", required: false}, scopes: {type: "string[]", required: true}, revoked: {type: "date", required: false}, referenceId: {type: "string", required: false}, authTime: {type: "date", required: false}, refreshId: {type: "string", required: false}, createdAt: {type: "date", required: true, default_value: -> { Time.now }}, updatedAt: {type: "date", required: true, default_value: -> { Time.now }, on_update: -> { Time.now }} } }, oauthConsent: { modelName: "oauthConsent", fields: { clientId: {type: "string", required: true}, userId: {type: "string", required: false}, referenceId: {type: "string", required: false}, scopes: {type: "string[]", required: true}, createdAt: {type: "date", required: true, default_value: -> { Time.now }}, updatedAt: {type: "date", required: true, default_value: -> { Time.now }, on_update: -> { Time.now }} } } } end |
.oauth_public_client_response(client) ⇒ Object
905 906 907 908 909 910 911 912 913 914 915 916 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 905 def oauth_public_client_response(client) data = OAuthProtocol.stringify_keys(client) { client_id: data["clientId"], client_name: data["name"], client_uri: data["uri"], logo_uri: data["icon"], contacts: data["contacts"] || [], tos_uri: data["tos"], policy_uri: data["policy"] }.compact end |
.oauth_rate_limit_rule(rate_limit, key, path, window:, max:) ⇒ Object
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 1076 def oauth_rate_limit_rule(rate_limit, key, path, window:, max:) override = rate_limit[key] return nil if override == false override = normalize_hash(override || {}) { path_matcher: ->(request_path) { request_path == path }, window: override[:window] || window, max: override[:max] || max } end |
.oauth_redirect_location ⇒ Object
585 586 587 588 589 590 591 592 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 585 def oauth_redirect_location yield rescue APIError => error location = error.headers["location"] return location if location raise end |
.oauth_redirect_with_code(ctx, config, query, session, client, scopes) ⇒ Object
694 695 696 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 694 def oauth_redirect_with_code(ctx, config, query, session, client, scopes) raise ctx.redirect((ctx, config, query, session, client, scopes)) end |
.oauth_register_client_endpoint(config) ⇒ Object
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 160 def oauth_register_client_endpoint(config) Endpoint.new(path: "/oauth2/register", method: "POST") do |ctx| session = Routes.current_session(ctx, allow_nil: true) body = OAuthProtocol.stringify_keys(ctx.body) unless config[:allow_dynamic_client_registration] raise APIError.new("FORBIDDEN", message: "Client registration is disabled") end unless session || config[:allow_unauthenticated_client_registration] raise APIError.new("UNAUTHORIZED") end if body.key?("skip_consent") || body.key?("skipConsent") raise APIError.new("BAD_REQUEST", message: "skip_consent is not allowed during dynamic client registration") end body["require_pkce"] = true unless body.key?("require_pkce") || body.key?("requirePKCE") client = OAuthProtocol.create_client( ctx, model: "oauthClient", body: body, owner_session: session, unauthenticated: session.nil?, default_scopes: config[:client_registration_default_scopes] || config[:scopes], allowed_scopes: config[:client_registration_allowed_scopes] || config[:scopes], store_client_secret: config[:store_client_secret], prefix: config[:prefix], dynamic_registration: true ) ctx.json(client, status: 201, headers: {"Cache-Control" => "no-store", "Pragma" => "no-cache"}) end end |
.oauth_revoke_endpoint(config) ⇒ Object
751 752 753 754 755 756 757 758 759 760 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 751 def oauth_revoke_endpoint(config) Endpoint.new(path: "/oauth2/revoke", method: "POST", metadata: {allowed_media_types: ["application/x-www-form-urlencoded", "application/json"]}) do |ctx| OAuthProtocol.authenticate_client!(ctx, "oauthClient", store_client_secret: config[:store_client_secret], prefix: config[:prefix]) body = OAuthProtocol.stringify_keys(ctx.body) if (token = OAuthProtocol.find_token_by_hint(config[:store], body["token"].to_s, body["token_type_hint"], prefix: config[:prefix])) token["revoked"] = Time.now end ctx.json({revoked: true}) end end |
.oauth_rotate_client_secret_endpoint(config) ⇒ Object
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 322 def oauth_rotate_client_secret_endpoint(config) Endpoint.new(path: "/oauth2/client/rotate-secret", method: "POST") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "rotate") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) client_data = OAuthProtocol.stringify_keys(client) raise APIError.new("BAD_REQUEST", message: "public clients cannot rotate secrets") if client_data["public"] || client_data["tokenEndpointAuthMethod"] == "none" client_secret = Crypto.random_string(32) updated = ctx.context.adapter.update( model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}], update: {clientSecret: OAuthProtocol.store_client_secret_value(ctx, client_secret, config[:store_client_secret]), updatedAt: Time.now} ) response = OAuthProtocol.client_response(updated, include_secret: false) ctx.json(response.merge(client_secret: OAuthProtocol.apply_prefix(client_secret, config[:prefix], :client_secret), client_secret_expires_at: client_data["clientSecretExpiresAt"] || 0)) end end |
.oauth_server_metadata_endpoint(config) ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 99 def (config) Endpoint.new(path: "/.well-known/oauth-authorization-server", method: "GET", metadata: {hide: true}) do |ctx| base = OAuthProtocol.endpoint_base(ctx) = { issuer: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)), authorization_endpoint: "#{base}/oauth2/authorize", token_endpoint: "#{base}/oauth2/token", registration_endpoint: "#{base}/oauth2/register", introspection_endpoint: "#{base}/oauth2/introspect", revocation_endpoint: "#{base}/oauth2/revoke", response_types_supported: ["code"], response_modes_supported: ["query"], grant_types_supported: config[:grant_types], token_endpoint_auth_methods_supported: oauth_token_auth_methods(config), introspection_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], revocation_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], code_challenge_methods_supported: ["S256"], authorization_response_iss_parameter_supported: true, scopes_supported: config.dig(:advertised_metadata, :scopes_supported) || config[:scopes] } [:jwks_uri] = oauth_jwks_uri(config) if oauth_jwks_uri(config) ctx.json(, headers: ) end end |
.oauth_signed_query(ctx, query) ⇒ Object
544 545 546 547 548 549 550 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 544 def oauth_signed_query(ctx, query) data = OAuthProtocol.stringify_keys(query).compact data["exp"] = (Time.now.to_i + 600).to_s unsigned = URI.encode_www_form(data) signature = Crypto.hmac_signature(unsigned, ctx.context.secret, encoding: :base64url) "#{unsigned}&#{URI.encode_www_form("sig" => signature)}" end |
.oauth_store_consent(ctx, client, session, scopes) ⇒ Object
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 712 def (ctx, client, session, scopes) client_id = OAuthProtocol.stringify_keys(client)["clientId"] user_id = session[:user]["id"] existing = ctx.context.adapter.find_one( model: "oauthConsent", where: [ {field: "clientId", value: client_id}, {field: "userId", value: user_id} ] ) data = {clientId: client_id, userId: user_id, scopes: scopes} if existing ctx.context.adapter.update(model: "oauthConsent", where: [{field: "id", value: existing.fetch("id")}], update: data) else ctx.context.adapter.create(model: "oauthConsent", data: data) end end |
.oauth_token_auth_methods(config) ⇒ Object
928 929 930 931 932 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 928 def oauth_token_auth_methods(config) methods = ["client_secret_basic", "client_secret_post"] methods.unshift("none") if config[:allow_unauthenticated_client_registration] methods end |
.oauth_token_endpoint(config) ⇒ Object
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 620 def oauth_token_endpoint(config) Endpoint.new(path: "/oauth2/token", method: "POST", metadata: {allowed_media_types: ["application/x-www-form-urlencoded", "application/json"]}) do |ctx| body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.authenticate_client!(ctx, "oauthClient", store_client_secret: config[:store_client_secret], prefix: config[:prefix]) client_grants = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(client)["grantTypes"]) if client_grants.any? && !client_grants.include?(body["grant_type"].to_s) raise APIError.new("BAD_REQUEST", message: "unsupported_grant_type") end audience = oauth_validate_resource!(ctx, config, body) response = case body["grant_type"] when OAuthProtocol::AUTH_CODE_GRANT code = OAuthProtocol.consume_code!( config[:store], body["code"], client_id: body["client_id"], redirect_uri: body["redirect_uri"], code_verifier: body["code_verifier"] ) OAuthProtocol.issue_tokens( ctx, config[:store], model: "oauthAccessToken", client: client, session: code[:session], scopes: code[:scopes], include_refresh: code[:scopes].include?("offline_access") || OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(client)["grantTypes"]).include?(OAuthProtocol::REFRESH_GRANT), issuer: OAuthProvider.validate_issuer_url(OAuthProtocol.issuer(ctx)), prefix: config[:prefix], refresh_token_expires_in: config[:refresh_token_expires_in], audience: audience, grant_type: OAuthProtocol::AUTH_CODE_GRANT, custom_token_response_fields: config[:custom_token_response_fields], custom_access_token_claims: config[:custom_access_token_claims], jwt_access_token: oauth_jwt_access_token?(config, audience), pairwise_secret: config[:pairwise_secret], nonce: code[:nonce], auth_time: code[:auth_time], reference_id: code[:reference_id] ) when OAuthProtocol::CLIENT_CREDENTIALS_GRANT requested = OAuthProtocol.parse_scopes(body["scope"]) allowed = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(client)["scopes"] || config[:scopes]) unless requested.all? { |scope| allowed.include?(scope) } raise APIError.new("BAD_REQUEST", message: "invalid_scope") end OAuthProtocol.issue_tokens(ctx, config[:store], model: "oauthAccessToken", client: client, session: {"user" => {}, "session" => {}}, scopes: requested, include_refresh: false, issuer: OAuthProtocol.issuer(ctx), prefix: config[:prefix], audience: audience, grant_type: OAuthProtocol::CLIENT_CREDENTIALS_GRANT, custom_token_response_fields: config[:custom_token_response_fields], custom_access_token_claims: config[:custom_access_token_claims], jwt_access_token: oauth_jwt_access_token?(config, audience), pairwise_secret: config[:pairwise_secret]) when OAuthProtocol::REFRESH_GRANT OAuthProtocol.refresh_tokens(ctx, config[:store], model: "oauthAccessToken", client: client, refresh_token: body["refresh_token"], scopes: body["scope"], issuer: OAuthProtocol.issuer(ctx), prefix: config[:prefix], refresh_token_expires_in: config[:refresh_token_expires_in], audience: audience, custom_token_response_fields: config[:custom_token_response_fields], custom_access_token_claims: config[:custom_access_token_claims], jwt_access_token: oauth_jwt_access_token?(config, audience), pairwise_secret: config[:pairwise_secret]) else raise APIError.new("BAD_REQUEST", message: "unsupported_grant_type") end ctx.json(response) end end |
.oauth_update_client_endpoint(config) ⇒ Object
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 275 def oauth_update_client_endpoint(config) Endpoint.new(path: "/oauth2/update-client", method: "POST") do |ctx| session = Routes.current_session(ctx) oauth_assert_client_privilege!(ctx, config, session, "update") body = OAuthProtocol.stringify_keys(ctx.body) client = OAuthProtocol.find_client(ctx, "oauthClient", body["client_id"]) raise APIError.new("NOT_FOUND", message: "client not found") unless client oauth_assert_owned_client!(client, session, config) update_source = OAuthProtocol.stringify_keys(body["update"] || {}) update = oauth_client_update_data(update_source) updated = update.empty? ? client : ctx.context.adapter.update(model: "oauthClient", where: [{field: "clientId", value: body["client_id"]}], update: update.merge(updatedAt: Time.now)) ctx.json(OAuthProtocol.client_response(updated, include_secret: false)) end end |
.oauth_update_consent_endpoint ⇒ Object
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 369 def Endpoint.new(path: "/oauth2/update-consent", method: "POST") do |ctx| session = Routes.current_session(ctx) body = OAuthProtocol.stringify_keys(ctx.body) id = body["id"] = if id.to_s.empty? (ctx, session, body["client_id"]) else ctx.context.adapter.find_one(model: "oauthConsent", where: [{field: "id", value: id}]) end raise APIError.new("NOT_FOUND", message: "missing id") if id.to_s.empty? && body["client_id"].to_s.empty? raise APIError.new("NOT_FOUND", message: "consent not found") unless = OAuthProtocol.stringify_keys() raise APIError.new("UNAUTHORIZED") unless ["userId"] == session[:user]["id"] client = OAuthProtocol.find_client(ctx, "oauthClient", ["clientId"]) allowed = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(client || {})["scopes"]) scopes = OAuthProtocol.parse_scopes(OAuthProtocol.stringify_keys(body["update"] || {})["scopes"] || body["scope"] || body["scopes"]) unless scopes.all? { |scope| allowed.include?(scope) } raise APIError.new("BAD_REQUEST", message: "invalid_scope") end updated = ctx.context.adapter.update( model: "oauthConsent", where: [{field: "id", value: ["id"]}], update: {scopes: scopes, updatedAt: Time.now} ) ctx.json((updated)) end end |
.oauth_userinfo_endpoint(config) ⇒ Object
762 763 764 765 766 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 762 def oauth_userinfo_endpoint(config) Endpoint.new(path: "/oauth2/userinfo", method: "GET") do |ctx| ctx.json(OAuthProtocol.userinfo(config[:store], ctx.headers["authorization"], additional_claim: config[:custom_user_info_claims] || config[:additional_claim], prefix: config[:prefix])) end end |
.oauth_validate_resource!(ctx, config, body) ⇒ Object
947 948 949 950 951 952 953 954 955 956 957 958 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 947 def oauth_validate_resource!(ctx, config, body) resources = Array(body["resource"]).compact.map(&:to_s) return nil if resources.empty? valid = Array(config[:valid_audiences]).map(&:to_s) return (resources.length == 1) ? resources.first : resources if valid.empty? resources.each do |resource| raise APIError.new("BAD_REQUEST", message: "requested resource invalid") unless valid.include?(resource) end (resources.length == 1) ? resources.first : resources end |
.oauth_verified_query!(ctx, oauth_query) ⇒ Object
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 |
# File 'lib/better_auth/plugins/oauth_provider.rb', line 552 def oauth_verified_query!(ctx, oauth_query) raise APIError.new("BAD_REQUEST", message: "missing oauth query") if oauth_query.to_s.empty? pairs = URI.decode_www_form(oauth_query.to_s) signature = pairs.reverse_each.find { |key, _value| key == "sig" }&.last unsigned_pairs = pairs.filter_map { |key, value| [key, value] unless key == "sig" } unsigned = URI.encode_www_form(unsigned_pairs) exp = unsigned_pairs.reverse_each.find { |key, _value| key == "exp" }&.last.to_i unless signature && exp >= Time.now.to_i && Crypto.verify_hmac_signature(unsigned, signature, ctx.context.secret, encoding: :base64url) raise APIError.new("BAD_REQUEST", message: "invalid oauth query") end unsigned_pairs.each_with_object({}) do |(key, value), result| next if key == "exp" result[key] = if result.key?(key) Array(result[key]) << value else value end end end |