这段时间公司开发项目用到oAuth2协议,现在做一下梳理。
CORS即Cross Origin Resouce Share,跨域资源共享;是W3C为防止脚本攻击,而制定的安全标准之一,它允许浏览器向跨域服务器发送XMLHttpRequest请求;
跨域域问题,伴随而来的就是前端项目中的权限认证问题。
1. 基本逻辑:
CORS跨域请求分为两种:简单请求、非简单请求,两种情景处理具体细节不同,但实现逻辑相同
简单请求需同时满足以下两个条件:
- 请求方法为:
GET
、HEAD
、POST
三种其中的一种; - HTTP头信息不超出一下几个字段:
①Accept ②Accept-Language ③Last-Event-ID ④Content ⑤Content-Type:只限三种:application/x-www-form-urlencoded、muiltipart/form-data、text/plain 简单请求流程:
①浏览器检测到请求为跨域请求时,便在请求头上加上字段Origin
,指明发出跨域请求的源;
②服务器端检测到跨域请求头信息中,Origin
是否在许可范围内:
③若请求源在允许范围,返回响应,响应头上添加以下几个字段:1234Access-Control-Allow-Origin:http://api.beta.com //服务器应许跨域白名单Access-Control-Allow-Credentials:true //允许跨域请求携带cookieAccess-Control-Expose-Headers:Custom-header //允许客户端请求时携带自定义头字段Conten-Type:text/html;chartset=utf-8 //允许返回数据类型④若跨域请求源不在允许范围内,服务器会返回一个XMLHttpRequest错误信息,该错误不能被http错误处理机制捕获,因为其状态码为200.
- 请求方法为:
非简单请求:
- 非简单请求,通常是对服务器有特殊需求的请求,
- 非简单请求发送前,浏览器会自动发送一次预检请求,请求方法为Option
- 预检请求通过后,后续步骤同简单请求
oAuth2认证逻辑步骤
- 用户使用用户名、密码登录;
- 后台校验用户信息;
- 跳转至oAuth认证接口,返回token、refresh token、token expires;(此处token一般有有效期)
- 用户携带token值与后台DB服务通过http/https交互;
- token 值到期后;用户携带refresh token请求oAuth token刷新接口更新token并通过响应发送至客户;
- 重复第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
返回结果样例:
|
|
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
返回结果
3. CORS仅仅是实现跨域请求的一种,还有其他多种方案,如
jsonp、document.domain、window.name、window.postMessage、CSST(css text Transformation)、flash等。
–end