# spring4
**Repository Path**: homeOFlimu/spring4
## Basic Information
- **Project Name**: spring4
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2020-05-18
- **Last Updated**: 2020-12-20
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
实验四
课程名称:企业级开发框架专题
学期:2020春季
|
实验名称 | 基于Spring Security码云OAuth2认证 | 实验序号 | 四 |
|
姓 名 | 利牧 | 学 号 | 201741412124 | 班 级 | 17软卓1班 |
|
实验地点 | | 实验日期 | 2020/5/18 | 指导老师 | 黎志雄 |
|
教师评语 | *** | 实验成绩 | 评阅教师 |
| 百分制 | ** |
|
同组同学 | 无 |
### 一、 实验目的
1、 掌握使用Spring Security框架;
2、 掌握配置Spring Security的安全过滤链;
3、 掌握编写Spring Security单元测试;
4、 掌握创建接入码云的应用;
5、 掌握码云OAuth2认证基本流程;
6、 掌握使用码云API;
7、 了解使用模板引擎或前端框架制作用户登录界面。
### 二、实验步骤
#### 1、创建接入码云的应用。

#### 2、编写重定向过滤器。
```
response.sendRedirect(String.format("https://gitee.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code", CLIENT_ID, REDIRECT_URI));
```
#### 3、编写get access_token。
```JAVA
String request_url = UriComponentsBuilder.fromUriString(ACCESS_TOKEN_API_URI)
.buildAndExpand(code, CLIENT_ID, REDIRECT_URI, CLIENT_SECRET).toString();
RequestEntity requestEntity = RequestEntity.post(URI.create(request_url))
.headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
.build();
ResponseEntity response = rest.exchange(requestEntity, String.class);
return response.getBody();
```
#### 4、编写getuserInfo。
```
String request_url = UriComponentsBuilder.fromUriString(USER_INFO_URI)
.buildAndExpand(accessToken).toString();
RequestEntity requestEntity = RequestEntity.get(URI.create(request_url))
.headers(httpHeaders -> {
httpHeaders.add("User-Agent", "Mozilla/5.0");
})
.build();
ResponseEntity responseEntity = rest.exchange(requestEntity, String.class);
String json = responseEntity.getBody();
Map res = new JacksonJsonParser().parseMap(json);
return res;
```
#### 5、编写安全过滤链
```
http.addFilterAfter(new GiteeOAuth2RedirectFilter(), SecurityContextPersistenceFilter.class);
http.addFilterAfter(new GiteeOAuth2LoginAuthenticationFilter(), SecurityContextPersistenceFilter.class);
```
#### 6、改造/user接口
```
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserInfo u = (UserInfo) authentication.getPrincipal();
model.addAttribute("userInfo",u.getUser());
return "user";
```
#### 7、运行结果

#### 7、测试,访问受保护的接口/test
```
@Test
@WithMockUser(authorities = "USER")
public void test() throws Exception {
////////////////////////////////////////////
/// 步骤八:模拟一个登录用户,访问受保护的接口/test,断言接口的返回内容body部分是否一致。
////////////////////////////////////////////
mvc.perform(MockMvcRequestBuilders.get("/test"))
.andExpect(MockMvcResultMatchers.content().string("访问/test接口成功,你拥有USER权限"));
}
```
