何宏伟

From Unsplash

[嵌牛导读]

通过上一篇文章OAuth设计机制及原理介绍的OAuth的认证思路以及授权方式,最最常用的授权码模式,通过本文的Unsplash Photos示例,帮助你正确的理解和熟悉OAuth的认证流程,并且完成资源获取

Unsplash Photos采用Vue实现,用来获取Unsplash丰富的照片资源,作为照片墙展示或者壁纸制作。

[嵌牛鼻子]

OAuth,授权码模式(Authrization Code)

[嵌牛提问]

按照本文示例应用的流程,当你自己梳理通过后,今后的OAuth认证资源访问应用都不再是问题

[嵌牛正文]

一. 开发流程

Unsplash官方文档认证流程如下:

1.

应用中引导用户到这个地址 https://unsplash.com/oauth/authorize 完成认证

  • client_id: 你的应用ID(第三方应用ID)
  • redirect_uri: 用户授权后的回调地址
  • response——type: 用户成功授权后返回的授权码响应,默认为“code”
  • scope: 通过“+ ”符号拼接的授权范围,例如public+read_user
    用户在第三方应用处进行授权,第三方列出权限范围供用户选择
2.

用户在授权后,将会被引导至redirect_uri这个回调地址,并携带授权码code

3.

第三方客户端通过HTTP协议发送POST请求,携带如下参数:

  • client_id: 你的应用ID(第三方应用ID)
  • secret: 你的应用密钥(第三方应用密钥)
  • redirect_uri: 应用回调地址
  • code: 用户成功授权后返回的授权码(上一 步得到的code
  • scope: 通过“+ ”符号拼接的授权范围,例如public+read_user
  • grant_type: 值为authorization_code

POST请求成功后会获得JSON格式响应,如下:

{
   "access_token": "091343ce13c8ae780065ecb3b13dc903475dd22cb78a05503c2e0c69c5e98044",
   "token_type": "bearer",
   "scope": "public read_photos write_photos",
   "created_at": 1436544465
 }
4.

On future requests, send OAuth Bearer access token via the HTTP Authorization header: Authorization: Bearer ACCESS_TOKEN

在之后的请求中,你需要在HTTP请求中header中加入上述参数

二. Unsplash Photos 开发

在实际开发中大家可以通过Ajax发送HTTP请求来进行开发,而我使用官方提供的Unspalsh-js - Node开发包,实际原理是一致的。

点击初始化跳转到认证地址
  • 获取授权码code:
            this.unsplash = new Unsplash({
                applicationId: this.loginCode.applicationId,
                secret: this.loginCode.secret,
                callbackUrl: this.loginCode.callbackUrl
            })
    
            this.authenticationUrl = this.unsplash.auth.getAuthenticationUrl([
                'public',
                'read_user'
            ])
            // 引导用户授权
            location.assign(this.authenticationUrl)
授权

授权成功后返***调地址处,注意URL处code
  • 获取token(后端执行用户不可见)
            // 携带上一步获得的code申请token
            this.unsplash.auth.userAuthentication(this.code)
            .then(toJson)
            .then(json => {
                this.unsplash.auth.setBearerToken(json.access_token)
            })
  • 申请token成功后就可获取资源,比如个人资料:
            this.unsplash.currentUser.profile()
            .then(toJson)
            .then(json => {
                console.log(json)
                this.currentUserProfile = json
                console.log(json.profile_image)
                this.src = this.currentUserProfile.profile_image.large
            })
个人头像获取
  • 通过用户输入的关键词获取对应的图片:
        handleQueryPhotos() {
            if (this.photo_key) {
                this.unsplash.search.photos(this.photo_key, 1, 12)
                .then(toJson)
                .then(json => {
                    json.results.forEach(element => {
                        this.photoList.push(element.urls.small)  
                    })
                })
            }
        }
查询fower的结果

END
参观地址:Unsplash Photos

收藏
评论加载中...