| |
| ## 基于 OAuth2 认证的资源接口请求方式 |
| |
| |
| ### 流程图 |
| |
|  |
| |
| |
| ### 项目配置 |
| |
| 1、在 ClientApplication(项目启动类)中,添加注解 @EnableInfrasOAuth2 |
| |
| 注,不能同时存在 注解 @EnableInfrasApiSecurity |
| |
| |
| |
| ### 认证 |
| |
| 1、浏览器请求 |
| ``` |
| http://localhost:8080/oauth/authorize?response_type=code&client_id=app&redirect_uri=http://example.com/index.html |
| ``` |
| |
| 显示登录页面,用户登录 |
| |
|  |
| |
| |
| 登录后显示 Scope 授权页面,用户选择 Approve,并授权即可 |
| |
|  |
| |
| |
| ### 返回 code |
| |
| 1、浏览器重定向 |
| |
| 参考地址: |
| ``` |
| http://example.com/index.html?code=SX1AUm |
| ``` |
| |
| ### 根据 code 获取 access_token |
| |
| curl 请求示例:curl 通过 Header 传递 client_id, client_secret |
| ``` |
| 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" |
| ``` |
| 注: |
| -H "Authorization: Basic YXBwOnNlY3JldA==" 为请求头参数 |
| -d "grant_type=authorization_code&code=SX1AUm&redirect_uri=http://example.com/index.html" 为POST提交数据 |
| |
| |
| 响应结果: |
| ``` |
| { |
| "access_token":"5f113f2d-b016-42fd-8353-b6b750426108", |
| "token_type":"bearer", |
| "refresh_token":"1400db36-f93a-4773-8cba-af370bac717a", |
| "expires_in":43199, |
| "scope":"app" |
| } |
| ``` |
| |
| |
| ### 根据 access_token 请求接口资源 |
| |
| curl 请求示例:curl 通过 Header 传递 access_token |
| ``` |
| curl -i -s -X GET -H "Authorization: Bearer 5f113f2d-b016-42fd-8353-b6b750426108" "http://localhost:8080/api/user" |
| ``` |
| 注: |
| -H "Authorization: Bearer 5f113f2d-b016-42fd-8353-b6b750426108" 为请求头参数 |
| |
| 响应结果: |
| ``` |
| { |
| "username":"user", |
| "password":null, |
| "authorities":[{"authority":"ROLE_ADMIN"},{"authority":"administrator"},{"authority":"user"}], |
| "accountNonExpired":true, |
| "accountNonLocked":true, |
| "credentialsNonExpired":true, |
| "enabled":true |
| } |
| ``` |