网站需要使用apple 三方登录,研究了一下,记录如下:
目录
配置
正式开发(oauth2.0)
1.登录授权页面
2.接收授权码code,向apple服务器申请token
我们拥有一个苹果开发者账号后,需要进行相关配置,会得到一些id和文件,苹果官方配置文档如下:https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple
1.配置结束后,将获得俩个文件 三个ID和一个回调URL
redirectURI = 'https://abc.baidu.com/appleAuth' // 自己设置的重定向域名,可添加多个
webClientId = 'com.baidu.abc.signInWithApple'; // 设置的client_id,一般是域名的反写
teamId = 'JI87S9KI7D'; // 10个字符的team_id
keyId = 'KOI98S78J6'; // 获取的10个字符的密钥标识符
2.一个以p8结尾的文件,用作生成jwt 用来请求token
正式开发前,可以先熟悉一下oauth2.0的认证流程
1.用户点击 导向到认证服务器
2.用户选择是否授权
3.授权后,认证服务器会带着授权码code请求重定向url
4.客户端获取到授权码code后,发送到后端服务器,然后用授权码code请求认证服务器
5.认证服务器验证授权码code 没问题后,返回access token 和refresh token
苹果官方文档
前端文档:
https://developer.apple.com/documentation/sign_in_with_apple
后端文档:https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api
就是一个html页面,会显示一个苹果登录的按钮,点击登录按钮后,会跳转到认证页面
代码如下:
clientId:配置获得
scope:权限范围,用来获取用户信息 email name 其中一个或者两个都设置
redirectURI:回调url,用户同意授权后,会带code向回调url 发起一个post请求,后端服务器需要去接受授权码code,然后去申请令牌
state:可以设定任意值,苹果认证服务器会返回这个值,可以利用这个参数来进行一些判断
我开发过程中,自己测试是利用上面的html页面,正式开发是手动拼接跳转授权页地址。
https://appleid.apple.com/auth/authorize?client_id=xxxxxxxxx&redirect_uri=xxxxxxxxx&response_type=xxxxxxxx&scope=
email name&response_mode=[RESPONSE_MODE]&state=xxxxxxxxx
如果手动拼接的话response_type
应设为code
,response_mode
应设为form_post
用户授权后,会向设置的 redirect_uri带着code发送一个post请求,还有设置的state,id_token(第一次授权登录没有这个字段),如果第一次授权登录,会返回用户信息user(第一次登录才有user信息,后面不能获取到,需要保存到服务端,如果再次获取,需要用户手动取消appleid在该应用程序上的授权)
苹果官方文档如下,H
andle the Response部分有对返回参数的解释
https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms
特别注意 :用户取消后,会返回error(user_cancelled_authorize)给redirect_uri,这种情况也是需要处理的
苹果post请求如下:
下一步做的是服务端发起一个post请求利用授权码code去申请令牌
苹果官方文档如下:
https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
请求的url为:POST https://appleid.apple.com/auth/token
注意: Content-Type: application/x-www-form-urlencoded
获取令牌参数:
grant_type
:'authorization_code'为获取令牌client_id
:client_idredirect_uri
:redirect_uricode
:上一步获取到的授权码,codeclient_secret
:一个生成的JWT
刷新令牌参数:
grant_type
:'refresh_token'为刷新令牌client_id
:client_idclient_secret
:client_secret,refresh_token
:上一步获取到的id_token
关于生成client_secret
:
苹果官方说生成jwt最长时间期限为6个月,可以每次都生成一个jwt
苹果官方文档 Creating the Client Secret 部分说明如下:
这里就需要用到上面获得的TEAM ID 、CLIENT ID 和 KEY ID
https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
然后我们服务端 post 请求到 https://appleid.apple.com/auth/token 来获取令牌,
获取参数如下:
其中的id_token 解密后,会获得用户信息 email和sub(用户身份标识),sub可以存到数据库与用户信息关联