Class: AuthingRuby::AuthenticationClient
- Inherits:
-
Object
- Object
- AuthingRuby::AuthenticationClient
- Defined in:
- lib/authing_ruby/authentication/AuthenticationClient.rb
Instance Method Summary collapse
-
#_buildOidcAuthorizeUrl(options = {}) ⇒ Object
私有函数,用于 buildAuthorizeUrl 处理 OIDC 协议 写法是完全参照的 JS SDK.
-
#_generateTokenRequest(params) ⇒ Object
逻辑参照 JS SDK 目的: 把 params 这个 hash 里 value 为空的值全部删掉 最后返回一个 url params 字符串.
- #_getAccessTokenByCodeWithClientSecretPost(code, options = {}) ⇒ Object
- #_getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken) ⇒ Object
- #_introspectTokenWithClientSecretPost(token) ⇒ Object
- #_revokeTokenWithClientSecretPost(token) ⇒ Object
-
#bindPhone(phone, phoneCode) ⇒ Object
绑定手机号 用户初次绑定手机号,如果需要修改手机号请使用 updatePhone 方法。如果该手机号已被绑定,将会绑定失败。发送验证码请使用 sendSmsCode 方法。.
-
#buildAuthorizeUrl(options = {}) ⇒ Object
TODO 生成 OIDC 协议的用户登录链接 文档: docs.authing.cn/v2/reference/sdk-for-node/authentication/StandardProtocol.html#%E7%94%9F%E6%88%90-oidc-%E5%8D%8F%E8%AE%AE%E7%9A%84%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95%E9%93%BE%E6%8E%A5 代码: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2098.
-
#checkLoggedIn ⇒ Object
checkLoggedIn 解释: 如果登录了,会返回唯一 id (userId) 如果没登录,会抛出错误.
-
#checkLoginStatus(token) ⇒ Object
检测 Token 登录状态.
-
#checkPasswordStrength(password) ⇒ Object
检查密码强度.
- #generateCodeChallenge ⇒ Object
-
#getAccessTokenByCode(code, options = {}) ⇒ Object
Code 换 Token 使用授权码 Code 获取用户的 Token 信息。 res = a.getAccessTokenByCode(‘授权码 code’); 参照: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L1977.
-
#getCodeChallengeDigest(options = {}) ⇒ Object
照搬 JS SDK 的逻辑.
-
#getCurrentUser ⇒ Object
获取当前登录的用户信息 返回:用户信息.
-
#getNewAccessTokenByRefreshToken(refreshToken) ⇒ Object
TODO 刷新 Access Token 使用 Refresh token 获取新的 Access token。 代码参考: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2296.
- #getUserInfoByAccessToken(access_token) ⇒ Object
-
#initialize(options = {}) ⇒ AuthenticationClient
constructor
A new instance of AuthenticationClient.
- #introspectToken(token) ⇒ Object
-
#loginByEmail(email, password, options = {}) ⇒ Object
使用邮箱登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.loginByEmail(‘[email protected]’, “123456789”).
-
#loginByPhoneCode(phone, code, options = {}) ⇒ Object
使用手机号验证码登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendSmsCode(“13556136684”) a.loginByPhoneCode(“13556136684”, “1347”).
-
#loginByPhonePassword(phone, password, options = {}) ⇒ Object
使用手机号密码登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByPhonePassword(“13556136684”, “123456”).
-
#loginByUsername(username, password, options = {}) ⇒ Object
使用用户名登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByUsername(‘agoodob’, “123456789”).
-
#logout ⇒ Object
退出登录.
-
#registerByEmail(email, password, profile = {}, options = {}) ⇒ Object
使用邮箱+密码注册 (完成, 测试通过) 参照: docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html 测试代码: a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByEmail(‘[email protected]’, “123456789”).
-
#registerByPhoneCode(phone, code, password, profile = {}, options = {}) ⇒ Object
使用手机号注册 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.registerByPhoneCode(“13556136684”, “6330”, “123456”).
-
#registerByUsername(username, password, profile = {}, options = {}) ⇒ Object
使用用户名注册 docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#%E4%BD%BF%E7%94%A8%E7%94%A8%E6%88%B7%E5%90%8D%E6%B3%A8%E5%86%8C a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByUsername(‘agoodob’, “123456789”).
-
#resetPasswordByPhoneCode(phone, code, newPassword) ⇒ Object
通过短信验证码重置密码.
-
#revokeToken(token) ⇒ Object
撤回 Access Token 或 Refresh token.
-
#sendEmail(email, scene) ⇒ Object
发送邮件 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendEmail(‘[email protected]’, “VERIFY_EMAIL”) * @param EmailScene scene 发送场景,可选值为 RESET_PASSWORD(发送重置密码邮件,邮件中包含验证码)、VerifyEmail(发送验证邮箱的邮件)、ChangeEmail(发送修改邮箱邮件,邮件中包含验证码).
-
#sendSmsCode(phone) ⇒ Object
发送短信验证码 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.sendSmsCode(“13556136684”).
- #setCurrentUser(user) ⇒ Object
- #setToken(token) ⇒ Object
-
#updatePassword(newPassword, oldPassword) ⇒ Object
更新用户密码.
-
#updateProfile(updates = {}) ⇒ Object
修改用户资料.
-
#validateToken(options = {}) ⇒ Object
TODO 检验 Id Token 合法性 通过 Authing 提供的在线接口验证 Id token 或 Access token。会产生网络请求。 文档: docs.authing.cn/v2/reference/sdk-for-node/authentication/StandardProtocol.html#%E6%A3%80%E9%AA%8C-id-token-%E5%90%88%E6%B3%95%E6%80%A7 代码参考: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2582.
Constructor Details
#initialize(options = {}) ⇒ AuthenticationClient
Returns a new instance of AuthenticationClient.
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 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 9 def initialize( = {}) @options = @appId = .fetch(:appId, nil) # 应用 ID @secret = .fetch(:secret, nil) # 应用密钥 @appHost = .fetch(:appHost, nil) # 该应用的域名 @redirectUri = .fetch(:redirectUri, nil) # 业务回调地址 @protocol = .fetch(:protocol, 'oidc') # 协议类型,可选值为 oidc、oauth、saml、cas # 公钥加密 @publicKeyManager = AuthingRuby::Common::PublicKeyManager.new() # 负责发送 GraphQL (其实就是 http) 请求的工具 graphqlEndpoint = "#{@appHost}/graphql/v2" @graphqlClient = AuthingRuby::Common::GraphqlClient.new(graphqlEndpoint, @options) # tokenProvider 只是存取一下 user 和 token @tokenProvider = Authentication::AuthenticationTokenProvider.new() @httpClient = AuthingRuby::Common::HttpClient.new(, @tokenProvider) @naiveHttpClient = AuthingRuby::Common::NaiveHttpClient.new(, @tokenProvider) # 把 GraphQL 文件夹路径放这里, 这些是私有变量 @folder_graphql = "./lib/graphql" @folder_graphql_mutation = "#{@folder_graphql}/mutations" @folder_graphql_query = "#{@folder_graphql}/queries" @baseClient = Authentication::BaseAuthenticationClient.new() # 以下几个参数主要用于 "标准协议认证模块" @tokenEndPointAuthMethod = .fetch(:tokenEndPointAuthMethod, 'client_secret_post') @introspectionEndPointAuthMethod = .fetch(:introspectionEndPointAuthMethod, 'client_secret_post') @revocationEndPointAuthMethod = .fetch(:revocationEndPointAuthMethod, 'client_secret_post') token = .fetch(:token, nil) if token setToken(token) end end |
Instance Method Details
#_buildOidcAuthorizeUrl(options = {}) ⇒ Object
私有函数,用于 buildAuthorizeUrl 处理 OIDC 协议 写法是完全参照的 JS SDK
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 311 def _buildOidcAuthorizeUrl( = {}) # 名字的映射 map = { appId: 'client_id', scope: 'scope', state: 'state', nonce: 'nonce', responseMode: 'response_mode', responseType: 'response_type', redirectUri: 'redirect_uri', codeChallenge: 'code_challenge', codeChallengeMethod: 'code_challenge_method' }; # 用来构造 url res = { nonce: AuthingRuby::Utils.randomNumberString(16), state: AuthingRuby::Utils.randomNumberString(16), scope: 'openid profile email phone address', client_id: @appId, redirect_uri: @redirectUri, response_type: 'code', }; map.each do |key, value| if [key.to_sym] # 如果 scope 的值里有 offline_access if value == 'scope' && .fetch(:scope, []).split(' ').include?("offline_access") res[:prompt] = 'consent' end res[value.to_sym] = [key] end end = @baseClient.appHost + '/oidc/auth?' + URI::QueryParams.dump(res) return end |
#_generateTokenRequest(params) ⇒ Object
逻辑参照 JS SDK 目的: 把 params 这个 hash 里 value 为空的值全部删掉 最后返回一个 url params 字符串
375 376 377 378 379 380 381 382 383 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 375 def _generateTokenRequest(params) ret = {} params.each do |key, value| if value ret[key] = value end end return URI::QueryParams.dump(ret) end |
#_getAccessTokenByCodeWithClientSecretPost(code, options = {}) ⇒ Object
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 385 def _getAccessTokenByCodeWithClientSecretPost(code, = {}) codeVerifier = .fetch(:codeVerifier, nil) qstr = _generateTokenRequest({ client_id: @appId, client_secret: @secret, grant_type: 'authorization_code', code: code, redirect_uri: @redirectUri, code_verifier: codeVerifier, }) api = '' if @protocol == 'oidc' api = "#{@baseClient.appHost}/oidc/token" elsif @protocol == 'oauth' api = "#{@baseClient.appHost}/oauth/token" end tokenSet = @naiveHttpClient.request({ method: 'POST', url: api, data: qstr, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) return tokenSet end |
#_getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken) ⇒ Object
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 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 464 def _getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken) qstr = _generateTokenRequest({ client_id: @appId, client_secret: @secret, grant_type: 'refresh_token', refresh_token: refreshToken }); api = '' if @protocol == 'oidc' api = "#{@baseClient.appHost}/oidc/token" elsif @protocol == 'oauth' api = "#{@baseClient.appHost}/oauth/token" end tokenSet = @naiveHttpClient.request({ method: 'POST', url: api, data: qstr, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); return tokenSet; end |
#_introspectTokenWithClientSecretPost(token) ⇒ Object
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 518 def _introspectTokenWithClientSecretPost(token) qstr = _generateTokenRequest({ client_id: @appId, client_secret: @secret, token: token, }) api = '' if @protocol == 'oidc' api = "#{@baseClient.appHost}/oidc/token/introspection" elsif @protocol == 'oauth' api = "#{@baseClient.appHost}/oauth/token/introspection" end tokenSet = @naiveHttpClient.request({ method: 'POST', url: api, data: qstr, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); return tokenSet; end |
#_revokeTokenWithClientSecretPost(token) ⇒ Object
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 757 def _revokeTokenWithClientSecretPost(token) qstr = _generateTokenRequest({ client_id: @appId, client_secret: @secret, token: token, }); api = ''; if @protocol === 'oidc' api = "#{@baseClient.appHost}/oidc/token/revocation"; elsif @protocol === 'oauth' api = "#{@baseClient.appHost}/oauth/token/revocation"; end tokenSet = @naiveHttpClient.request({ method: 'POST', url: api, data: qstr, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); return tokenSet; end |
#bindPhone(phone, phoneCode) ⇒ Object
绑定手机号 用户初次绑定手机号,如果需要修改手机号请使用 updatePhone 方法。如果该手机号已被绑定,将会绑定失败。发送验证码请使用 sendSmsCode 方法。
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 695 def bindPhone(phone, phoneCode) graphqlAPI = AuthingRuby::GraphQLAPI.new variables = { "phone": phone, "phoneCode": phoneCode, } res = graphqlAPI.bindPhone(@graphqlClient, @tokenProvider, variables) json = JSON.parse(res) user = json.dig("data", "bindPhone") if user setCurrentUser(user); return user; else return json end end |
#buildAuthorizeUrl(options = {}) ⇒ Object
TODO 生成 OIDC 协议的用户登录链接 文档: docs.authing.cn/v2/reference/sdk-for-node/authentication/StandardProtocol.html#%E7%94%9F%E6%88%90-oidc-%E5%8D%8F%E8%AE%AE%E7%9A%84%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95%E9%93%BE%E6%8E%A5 代码: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2098
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 352 def buildAuthorizeUrl( = {}) unless @appHost raise '请在初始化 AuthenticationClient 时传入应用域名 appHost 参数,形如:https://app1.authing.cn' end protocol = @options.fetch(:protocol, nil) if protocol == 'oidc' return _buildOidcAuthorizeUrl(); end if protocol == 'oauth' throw "oauth 协议暂未实现" end if protocol == 'saml' throw "saml 协议暂未实现" end if protocol == 'cas' throw "cas 协议暂未实现" end raise '不支持的协议类型,请在初始化 AuthenticationClient 时传入 protocol 参数,可选值为 oidc、oauth、saml、cas' end |
#checkLoggedIn ⇒ Object
checkLoggedIn 解释: 如果登录了,会返回唯一 id (userId) 如果没登录,会抛出错误
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 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 629 def checkLoggedIn() # 有 user 就直接返回 id user = @tokenProvider.getUser() if user return user.fetch("id", nil) # 608966b08b4af522620d2e59 end # 尝试获取 token token = @tokenProvider.getToken() if !token raise '请先登录!' # 例子: 如果 logout 了再次调用 checkLoggedIn 会报错,就是这里报错 end # 解码 token decoded_token_array = JWT.decode token, nil, false payload = decoded_token_array[0] # 从 token 中获取 user_id 并返回 userId = nil authing_sub = payload.fetch("sub", nil) id = payload.dig("data", "id") if authing_sub userId = authing_sub else userId = id end return userId end |
#checkLoginStatus(token) ⇒ Object
检测 Token 登录状态
670 671 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 670 def checkLoginStatus end |
#checkPasswordStrength(password) ⇒ Object
检查密码强度
661 662 663 664 665 666 667 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 661 def checkPasswordStrength(password) graphqlAPI = AuthingRuby::GraphQLAPI.new variables = { "password": password } res = graphqlAPI.checkPasswordStrength(@graphqlClient, @tokenProvider, variables) json = JSON.parse(res) return json.dig("data", "checkPasswordStrength") end |
#generateCodeChallenge ⇒ Object
730 731 732 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 730 def generateCodeChallenge() return AuthingRuby::Utils.generateRandomString(43); end |
#getAccessTokenByCode(code, options = {}) ⇒ Object
Code 换 Token 使用授权码 Code 获取用户的 Token 信息。 res = a.getAccessTokenByCode(‘授权码 code’); 参照: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L1977
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 417 def getAccessTokenByCode(code, = {}) # 检查参数合法性 if ['oauth', 'oidc'].include?(@protocol) == false raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数' end if !@secret && @tokenEndPointAuthMethod != nil raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数' end if @tokenEndPointAuthMethod == 'client_secret_post' return _getAccessTokenByCodeWithClientSecretPost(code, ) end if @tokenEndPointAuthMethod == 'client_secret_basic' # TODO raise "client_secret_basic 还未实现" # return _getAccessTokenByCodeWithClientSecretBasic(code, options.fetch(:codeVerifier, nil)) end if @tokenEndPointAuthMethod == nil # TODO raise "还未实现" # return _getAccessTokenByCodeWithNone(code, options.fetch(:codeVerifier, nil)) end end |
#getCodeChallengeDigest(options = {}) ⇒ Object
照搬 JS SDK 的逻辑
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 735 def getCodeChallengeDigest( = {}) if .empty? raise '请提供 options 参数,options.codeChallenge 为一个长度大于等于 43 的字符串,options.method 可选值为 S256、plain' end codeChallenge = .fetch(:codeChallenge, nil) method = .fetch(:method, 'S256') if codeChallenge == nil raise '请提供 options.codeChallenge,值为一个长度大于等于 43 的字符串' end if method == 'S256' base64 = Digest::SHA256.base64digest codeChallenge result = base64.gsub(/\+/, '-').gsub(/\//, '-').gsub(/=/, '') return result end if method == 'plain' return .codeChallenge; end raise '不支持的 options.method,可选值为 S256、plain' end |
#getCurrentUser ⇒ Object
获取当前登录的用户信息 返回:用户信息
278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 278 def getCurrentUser() graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.getCurrentUser(@graphqlClient, @tokenProvider, {}) json = JSON.parse(res) user = json.dig("data", "user") if user setCurrentUser(user) return user else return json end end |
#getNewAccessTokenByRefreshToken(refreshToken) ⇒ Object
TODO 刷新 Access Token 使用 Refresh token 获取新的 Access token。 代码参考: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2296
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 494 def getNewAccessTokenByRefreshToken(refreshToken) # 检查参数合法性 if ['oauth', 'oidc'].include?(@protocol) == false raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数' end if !@secret && @tokenEndPointAuthMethod != nil raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数' end if @tokenEndPointAuthMethod == 'client_secret_post' return _getNewAccessTokenByRefreshTokenWithClientSecretPost( refreshToken ); end if @tokenEndPointAuthMethod == 'client_secret_basic' # return await this._getNewAccessTokenByRefreshTokenWithClientSecretBasic( # refreshToken # ); end if @tokenEndPointAuthMethod == 'none' # return await this._getNewAccessTokenByRefreshTokenWithNone(refreshToken); end end |
#getUserInfoByAccessToken(access_token) ⇒ Object
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 446 def getUserInfoByAccessToken(access_token) api = nil; if @protocol == 'oidc' api = "#{@appHost}/oidc/me"; elsif @protocol == 'oauth' api = "#{@appHost}/oauth/me"; end userInfo = @naiveHttpClient.request({ method: 'POST', url: api, headers: { Authorization: 'Bearer ' + access_token } }); return userInfo end |
#introspectToken(token) ⇒ Object
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 545 def introspectToken(token) # 检查参数合法性 if ['oauth', 'oidc'].include?(@protocol) == false raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数' end if !@secret && @tokenEndPointAuthMethod != nil raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数' end if @introspectionEndPointAuthMethod == 'client_secret_post' return _introspectTokenWithClientSecretPost(token) end if @introspectionEndPointAuthMethod == 'client_secret_basic' # return await this._introspectTokenWithClientSecretBasic(token); end if @introspectionEndPointAuthMethod == 'none' # return await this._introspectTokenWithNone(token); end raise '初始化 AuthenticationClient 时传入的 introspectionEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none,请检查参数' end |
#loginByEmail(email, password, options = {}) ⇒ Object
使用邮箱登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.loginByEmail(‘[email protected]’, “123456789”)
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 151 def loginByEmail(email, password, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "email": email, "password": encryptedPassword, "autoRegister": .fetch(:autoRegister, nil), "captchaCode": .fetch(:captchaCode, nil), "clientIp": .fetch(:clientIp, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.loginByEmail(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'loginByEmail') if user setCurrentUser(user); return user end return json end |
#loginByPhoneCode(phone, code, options = {}) ⇒ Object
使用手机号验证码登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendSmsCode(“13556136684”) a.loginByPhoneCode(“13556136684”, “1347”)
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 208 def loginByPhoneCode(phone, code, = {}) # 第一步:构建 variables variables = { "input": { "phone": phone, "code": code, "clientIp": .fetch(:clientIp, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.loginByPhoneCode(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'loginByPhoneCode') if user setCurrentUser(user); return user end return json end |
#loginByPhonePassword(phone, password, options = {}) ⇒ Object
使用手机号密码登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByPhonePassword(“13556136684”, “123456”)
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 231 def loginByPhonePassword(phone, password, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "phone": phone, "password": encryptedPassword, "captchaCode": .fetch(:captchaCode, nil), "clientIp": .fetch(:clientIp, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.loginByPhonePassword(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'loginByPhonePassword') if user setCurrentUser(user); return user end return json end |
#loginByUsername(username, password, options = {}) ⇒ Object
使用用户名登录 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByUsername(‘agoodob’, “123456789”)
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 179 def loginByUsername(username, password, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "username": username, "password": encryptedPassword, "autoRegister": .fetch(:autoRegister, nil), "captchaCode": .fetch(:captchaCode, nil), "clientIp": .fetch(:clientIp, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.loginByUsername(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'loginByUsername') if user setCurrentUser(user); return user end return json end |
#logout ⇒ Object
退出登录
300 301 302 303 304 305 306 307 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 300 def logout() url = "#{@appHost}/api/v2/logout?app_id=#{@appId}" @httpClient.request({ method: 'GET', url: url, }); @tokenProvider.clearUser(); end |
#registerByEmail(email, password, profile = {}, options = {}) ⇒ Object
使用邮箱+密码注册 (完成, 测试通过) 参照: docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html 测试代码: a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByEmail(‘[email protected]’, “123456789”)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 54 def registerByEmail(email, password, profile = {}, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "email": email, "password": encryptedPassword, "profile": profile, "forceLogin": .fetch(:forceLogin, false), "clientIp": .fetch(:clientIp, nil), "context": .fetch(:context, nil), "generateToken": .fetch(:generateToken, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.registerByEmail(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'registerByEmail') return user if user return json end |
#registerByPhoneCode(phone, code, password, profile = {}, options = {}) ⇒ Object
使用手机号注册 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.registerByPhoneCode(“13556136684”, “6330”, “123456”)
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 123 def registerByPhoneCode(phone, code, password, profile = {}, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "phone": phone, "code": code, "password": encryptedPassword, "profile": profile, "forceLogin": .fetch(:forceLogin, false), "clientIp": .fetch(:clientIp, nil), "context": .fetch(:context, nil), "generateToken": .fetch(:generateToken, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.registerByPhoneCode(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'registerByPhoneCode') return user if user return json end |
#registerByUsername(username, password, profile = {}, options = {}) ⇒ Object
使用用户名注册 docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#%E4%BD%BF%E7%94%A8%E7%94%A8%E6%88%B7%E5%90%8D%E6%B3%A8%E5%86%8C a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByUsername(‘agoodob’, “123456789”)
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 82 def registerByUsername(username, password, profile = {}, = {}) # 第一步:构建 variables publicKey = @publicKeyManager.getPublicKey() encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey) variables = { "input": { "username": username, "password": encryptedPassword, "profile": profile, "forceLogin": .fetch(:forceLogin, false), "clientIp": .fetch(:clientIp, nil), "context": .fetch(:context, nil), "generateToken": .fetch(:generateToken, nil), } } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.registerByUsername(@graphqlClient, variables) json = JSON.parse(res) user = json.dig('data', 'registerByUsername') return user if user return json end |
#resetPasswordByPhoneCode(phone, code, newPassword) ⇒ Object
通过短信验证码重置密码
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 713 def resetPasswordByPhoneCode(phone, code, newPassword) publicKey = @publicKeyManager.getPublicKey() newPasswordEncrypted = AuthingRuby::Utils.encrypt(newPassword, publicKey) variables = { "phone": phone, "code": code, "newPassword": newPasswordEncrypted, } graphqlAPI = AuthingRuby::GraphQLAPI.new resp = graphqlAPI.resetPassword(@graphqlClient, @tokenProvider, variables) json = JSON.parse(resp) result = json.dig("data", "resetPassword") # {"message":"重置密码成功!","code":200} return result if result return json end |
#revokeToken(token) ⇒ Object
撤回 Access Token 或 Refresh token
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 781 def revokeToken(token) # 检查参数合法性 if ['oauth', 'oidc'].include?(@protocol) == false raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数' end if !@secret && @tokenEndPointAuthMethod != nil raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数' end if @revocationEndPointAuthMethod == 'client_secret_post' _revokeTokenWithClientSecretPost(token) # 实测这个请求啥也不返回, 空的, 所以把这个直接 return 返回没啥用 return true; end if @revocationEndPointAuthMethod == 'client_secret_basic' # await this._revokeTokenWithClientSecretBasic(token); # return true; end if @revocationEndPointAuthMethod == 'none' # await this._revokeTokenWithNone(token); # return true; end raise '初始化 AuthenticationClient 时传入的 revocationEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none,请检查参数' end |
#sendEmail(email, scene) ⇒ Object
发送邮件 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendEmail(‘[email protected]’, “VERIFY_EMAIL”)
-
@param EmailScene scene 发送场景,可选值为 RESET_PASSWORD(发送重置密码邮件,邮件中包含验证码)、VerifyEmail(发送验证邮箱的邮件)、ChangeEmail(发送修改邮箱邮件,邮件中包含验证码)
262 263 264 265 266 267 268 269 270 271 272 273 274 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 262 def sendEmail(email, scene) variables = { "email": email, "scene": scene, } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.sendEmail(@graphqlClient, variables) json = JSON.parse(res) data = json.dig('data') return data if data return json # {"sendEmail":{"message":"","code":200}} end |
#sendSmsCode(phone) ⇒ Object
发送短信验证码 a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.sendSmsCode(“13556136684”)
109 110 111 112 113 114 115 116 117 118 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 109 def sendSmsCode(phone) url = "#{@appHost}/api/v2/sms/send" graphqlClient = AuthingRuby::Common::GraphqlClient.new(url, @options) json = { "phone": phone } response = graphqlClient.request({json: json}) # {"code":200,"message":"发送成功"} return response end |
#setCurrentUser(user) ⇒ Object
291 292 293 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 291 def setCurrentUser(user) @tokenProvider.setUser(user); end |
#setToken(token) ⇒ Object
295 296 297 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 295 def setToken(token) @tokenProvider.setToken(token); end |
#updatePassword(newPassword, oldPassword) ⇒ Object
更新用户密码
679 680 681 682 683 684 685 686 687 688 689 690 691 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 679 def updatePassword(newPassword, oldPassword) publicKey = @publicKeyManager.getPublicKey() newPasswordEncrypted = AuthingRuby::Utils.encrypt(newPassword, publicKey) oldPasswordEncrypted = AuthingRuby::Utils.encrypt(oldPassword, publicKey) variables = { "newPassword": newPasswordEncrypted, "oldPassword": oldPasswordEncrypted, } graphqlAPI = AuthingRuby::GraphQLAPI.new res = graphqlAPI.updatePassword(@graphqlClient, @tokenProvider, variables) json = JSON.parse(res) return json.dig("data", "updatePassword") end |
#updateProfile(updates = {}) ⇒ Object
修改用户资料
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 605 def updateProfile(updates = {}) userId = checkLoggedIn() graphqlAPI = AuthingRuby::GraphQLAPI.new variables = { "id": userId, "input": updates } res = graphqlAPI.updateUser(@graphqlClient, @tokenProvider, variables) json = JSON.parse(res) updated_user = json.dig('data', 'updateUser') if updated_user # 如果更新成功,返回更新后的用户 setCurrentUser(updated_user) return updated_user else # 如果更新失败,返回原结果 # {"errors"=>[{"message"=>{"code"=>2020, "message"=>"尚未登录,无访问权限"}, "locations"=>[{"line"=>2, "column"=>3}], "path"=>["updateUser"], "extensions"=>{"code"=>"INTERNAL_SERVER_ERROR"}}], "data"=>nil} return json end end |
#validateToken(options = {}) ⇒ Object
TODO 检验 Id Token 合法性 通过 Authing 提供的在线接口验证 Id token 或 Access token。会产生网络请求。 文档: docs.authing.cn/v2/reference/sdk-for-node/authentication/StandardProtocol.html#%E6%A3%80%E9%AA%8C-id-token-%E5%90%88%E6%B3%95%E6%80%A7 代码参考: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2582
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 |
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 571 def validateToken( = {}) if .empty? raise '请在传入的参数对象中包含 accessToken 或 idToken 字段' end accessToken = .fetch(:accessToken, nil) idToken = .fetch(:idToken, nil) if accessToken != nil && idToken != nil raise "accessToken 和 idToken 只能传入一个,不能同时传入" end if idToken data = @naiveHttpClient.request({ url: "#{@baseClient.appHost}/api/v2/oidc/validate_token", method: 'GET', params: { id_token: idToken } }) return data elsif accessToken data = @naiveHttpClient.request({ url: "#{@baseClient.appHost}/api/v2/oidc/validate_token", method: 'GET', params: { access_token: accessToken } }); return data end end |