oAuth 认证

这段时间公司开发项目用到oAuth2协议,现在做一下梳理。

CORS即Cross Origin Resouce Share,跨域资源共享;是W3C为防止脚本攻击,而制定的安全标准之一,它允许浏览器向跨域服务器发送XMLHttpRequest请求;
跨域域问题,伴随而来的就是前端项目中的权限认证问题。

1. 基本逻辑:

跨域请求分为两种:简单请求、非简单请求,两种情景处理具体细节不同,但实现逻辑相同
1. 用户使用用户名、密码登录;
2. 后台校验用户信息;
3. 跳转至oAuth认证接口,返回token、refresh token、token expires;(此处token一般有有效期)
4. 用户携带token值与后台DB服务通过http/https交互;
5. token 值到期后;用户携带refresh token请求oAuth token刷新接口更新token并通过响应发送至客户;
6. 重复第4、第5步,保证token有效可用状态下,与后台进行交互

oAuth2的协议.里面有两个比较常用的接口.

1. 获取token

接口: /oauth/token?

参数: (grant_type是写规定好的,其它的两个自定义)

  • grant_type=password
  • username=development@sometech.com
  • password=oQd-BfT-cer-7LP

完整的样例:http://localhost:9000/oauth/token?grant_type=password&username=development@sometech.com&password=oQd-BfT-cer-7LP

返回结果样例:

{
    "access_token": "beeaa54e-8391-4de0-8ba6-ce145b3fb812",
    "token_type": "bearer",
    "refresh_token": "8129769a-d804-46c7-856a-3bacd409b650",
    "expires_in": 3599,
    "scope": "read write"
}

2. 刷新token

接口:http://localhost:9000/oauth/token?

参数:(refresh_token是根据1中的来定的.其它参数是固定的)

  • client_id=dashboard
  • client_secret=secret
  • grant_type=refresh_token
  • refresh_token=43dca105-627e-4f50-86e8-0c22c2f3abe9

样例: http://localhost:9000/oauth/token?client_id=dashboard&client_secret=secret&grant_type=refresh_token&refresh_token=43dca105-627e-4f50-86e8-0c22c2f3abe9

返回结果

{
    "access_token": "0135c92b-12ab-4af9-88f4-97ef85115e71",
    "token_type": "bearer",
    "refresh_token": "75d209b5-a30d-43a8-abcd-850e7fb62e76",
    "expires_in": 3599,
    "scope": "read write"
}

3. CORS仅仅是实现跨域请求的一种,还有其他多种方案,如

jsonp、document.domain、window.name、window.postMessage、CSST(css text Transformation)、flash等。

--end

原文地址:https://www.cnblogs.com/hbzyin/p/7161210.html