blob: 6a93b1b52b9b3911593a147ca504333d3841cfaf [file] [log] [blame]
刘洪青76d8b3d2018-08-22 10:32:57 +08001
2## 基于 OAuth2 认证的资源接口请求方式
3
4
5### 流程图
6
7![流程图](oauth2/OAuth2认证登录流程.png)
8
9
10### 项目配置
11
121、在 ClientApplication(项目启动类)中,添加注解 @EnableInfrasOAuth2
13
14注,不能同时存在 注解 @EnableInfrasApiSecurity
15
16
17
18### 认证
19
201、浏览器请求
21```
22http://localhost:8080/oauth/authorize?response_type=code&client_id=app&redirect_uri=http://example.com/index.html
23```
24
25显示登录页面,用户登录
26
27![登录页面](oauth2/oauth2-login.png)
28
29
30登录后显示 Scope 授权页面,用户选择 Approve,并授权即可
31
32![授权页面](oauth2/oauth2-approval.png)
33
34
35### 返回 code
36
371、浏览器重定向
38
39参考地址:
40```
41http://example.com/index.html?code=SX1AUm
42```
43
44### 根据 code 获取 access_token
45
46curl 请求示例:curl 通过 Header 传递 client_id, client_secret
47```
48curl -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
69curl 请求示例:curl 通过 Header 传递 access_token
70```
71curl -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```