刘洪青 | 76d8b3d | 2018-08-22 10:32:57 +0800 | [diff] [blame^] | 1 | |
| 2 | ## 基于 OAuth2 认证的资源接口请求方式 |
| 3 | |
| 4 | |
| 5 | ### 流程图 |
| 6 | |
| 7 |  |
| 8 | |
| 9 | |
| 10 | ### 项目配置 |
| 11 | |
| 12 | 1、在 ClientApplication(项目启动类)中,添加注解 @EnableInfrasOAuth2 |
| 13 | |
| 14 | 注,不能同时存在 注解 @EnableInfrasApiSecurity |
| 15 | |
| 16 | |
| 17 | |
| 18 | ### 认证 |
| 19 | |
| 20 | 1、浏览器请求 |
| 21 | ``` |
| 22 | http://localhost:8080/oauth/authorize?response_type=code&client_id=app&redirect_uri=http://example.com/index.html |
| 23 | ``` |
| 24 | |
| 25 | 显示登录页面,用户登录 |
| 26 | |
| 27 |  |
| 28 | |
| 29 | |
| 30 | 登录后显示 Scope 授权页面,用户选择 Approve,并授权即可 |
| 31 | |
| 32 |  |
| 33 | |
| 34 | |
| 35 | ### 返回 code |
| 36 | |
| 37 | 1、浏览器重定向 |
| 38 | |
| 39 | 参考地址: |
| 40 | ``` |
| 41 | http://example.com/index.html?code=SX1AUm |
| 42 | ``` |
| 43 | |
| 44 | ### 根据 code 获取 access_token |
| 45 | |
| 46 | curl 请求示例:curl 通过 Header 传递 client_id, client_secret |
| 47 | ``` |
| 48 | curl -i -s -X POST -H "Authorization: Basic YXBwOnNlY3JldA==" -d "grant_type=authorization_code&code=SX1AUm&redirect_uri=http://example.com/index.html" "http://localhost:8080/oauth/token" |
| 49 | ``` |
| 50 | 注: |
| 51 | -H "Authorization: Basic YXBwOnNlY3JldA==" 为请求头参数 |
| 52 | -d "grant_type=authorization_code&code=SX1AUm&redirect_uri=http://example.com/index.html" 为POST提交数据 |
| 53 | |
| 54 | |
| 55 | 响应结果: |
| 56 | ``` |
| 57 | { |
| 58 | "access_token":"5f113f2d-b016-42fd-8353-b6b750426108", |
| 59 | "token_type":"bearer", |
| 60 | "refresh_token":"1400db36-f93a-4773-8cba-af370bac717a", |
| 61 | "expires_in":43199, |
| 62 | "scope":"app" |
| 63 | } |
| 64 | ``` |
| 65 | |
| 66 | |
| 67 | ### 根据 access_token 请求接口资源 |
| 68 | |
| 69 | curl 请求示例:curl 通过 Header 传递 access_token |
| 70 | ``` |
| 71 | curl -i -s -X GET -H "Authorization: Bearer 5f113f2d-b016-42fd-8353-b6b750426108" "http://localhost:8080/api/user" |
| 72 | ``` |
| 73 | 注: |
| 74 | -H "Authorization: Bearer 5f113f2d-b016-42fd-8353-b6b750426108" 为请求头参数 |
| 75 | |
| 76 | 响应结果: |
| 77 | ``` |
| 78 | { |
| 79 | "username":"user", |
| 80 | "password":null, |
| 81 | "authorities":[{"authority":"ROLE_ADMIN"},{"authority":"administrator"},{"authority":"user"}], |
| 82 | "accountNonExpired":true, |
| 83 | "accountNonLocked":true, |
| 84 | "credentialsNonExpired":true, |
| 85 | "enabled":true |
| 86 | } |
| 87 | ``` |