使用者登入成功後都要進行身份認證,認證通過後才可以預約掛號。
認證過程:使用者填寫基本資訊(姓名、證件型別、證件號碼和證件照片),提交平臺稽核
使用者認證相關介面:
(1)上傳證件圖片
(2)提交認證
(3)獲取認證資訊
使用者認證需要上傳證件圖片,因此我們要做檔案服務,為了解決海量資料儲存與彈性擴容,專案中我們採用雲端儲存的解決方案:阿里雲OSS。
(1)申請阿里雲賬號
(2)實名認證
(3)開通「物件儲存OSS」服務
(4)進入管理控制檯
為Bucket起一個名字,其餘選項預設即可。
注意:專案中涉及身份證照片,讀寫許可權選擇預設的「私有」
得到endpoint:建立Bucket後,在概覽頁面可以獲取當前Bucket的endpoint值,這個值後面程式設計的時候會用到
建立一個資料夾,上傳一個檔案
AccessKeyId, AccessKeySecret
新增許可權:AliyunOSSFullAccess
在物件儲存首頁的右側,可以找到幫助檔案的入口
在service模組下建立子模組service-yun
在service-yun中引入依賴
<dependencies>
<!-- 阿里雲oss依賴 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<!--實體-->
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>model</artifactId>
<version>1.0</version>
</dependency>
<!--服務通用設定-->
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service-util</artifactId>
<version>1.0</version>
</dependency>
<!--時間日期工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--自定義安全模組-->
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>spring-security</artifactId>
<version>1.0</version>
</dependency>
<!-- 單元測試 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在server-yun模組中resources目錄下建立檔案
application.yml
:
spring:
application:
name: service-yun
profiles:
active: dev,redis
application-dev.yml
:
server:
port: 8204
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
logging:
level:
root: info
file:
path: yun
aliyun:
oss: #阿里雲 OSS
endpoint: your endpoint
key-id: your accessKeyId
key-secret: your accessKeySecret
bucket-name: your bucketname
建立ServiceYunApplication
package com.atguigu.syt.yun;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消資料來源設定自動讀取
@ComponentScan(basePackages = {"com.atguigu"})
public class ServiceYunApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceYunApplication.class, args);
}
}
在閘道器中設定如下內容:
- id: service-yun
predicates: Path=/*/yun/**
uri: lb://service-yun
建立常數讀取工具類:OssConstantProperties.java
package com.atguigu.syt.yun.utils;
@Configuration
@ConfigurationProperties(prefix="aliyun.oss") //讀取節點
@Data
public class OssConstantProperties {
private String endpoint;
private String keyId;
private String keySecret;
private String bucketName;
}
建立controller.front包,建立FrontFileController類
package com.atguigu.syt.yun.controller.front;
@Api(tags = "阿里雲檔案管理")
@RestController
@RequestMapping("/front/yun/file")
public class FrontFileController {
@Resource
private FileService fileService;
/**
* 檔案上傳
*/
@ApiOperation("檔案上傳")
@ApiImplicitParam(name = "file",value = "上傳檔案", required = true)
@PostMapping("/auth/upload")
public Result<Map<String, String>> upload(MultipartFile file) {
Map<String, String> map = fileService.upload(file);
return Result.ok(map);
}
}
介面:FileService
package com.atguigu.syt.oss.service;
public interface FileService {
/**
* 檔案上傳
* @param file
* @return
*/
Map<String, String> upload(MultipartFile file);
}
實現:FileServiceImpl
參考SDK中的:Java->上傳檔案->簡單上傳->流式上傳->上傳檔案流
package com.atguigu.syt.oss.service.impl;
@Service
@Slf4j
public class FileServiceImpl implements FileService {
@Resource
private OssConstantProperties ossConstantProperties;
/**
* 參考SDK中的:Java->上傳檔案->簡單上傳->流式上傳->上傳檔案流
* @param file
* @return
*/
@Override
public Map<String, String> upload(MultipartFile file) {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = ossConstantProperties.getEndpoint();
// 阿里雲賬號AccessKey擁有所有API的存取許可權,風險很高。強烈建議您建立並使用RAM使用者進行API存取或日常運維,請登入RAM控制檯建立RAM使用者。
String accessKeyId = ossConstantProperties.getKeyId();
String accessKeySecret = ossConstantProperties.getKeySecret();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = ossConstantProperties.getBucketName();
// 檔名稱
String originalFilename = file.getOriginalFilename();
String dateString = new DateTime().toString("yyyyMMdd");
// 填寫Object完整路徑,完整路徑中不能包含Bucket名稱,例如exampledir/exampleobject.txt。
String objectName =
dateString
+ "/" + UUID.randomUUID().toString().replace("-", "")
+ originalFilename.substring(originalFilename.lastIndexOf("."));
// 建立OSSClient範例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = file.getInputStream();
// 建立PutObjectRequest物件。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 設定該屬性可以返回response。如果不設定,則返回的response為空。
putObjectRequest.setProcess("true");
// 建立PutObject請求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
// 如果上傳成功,則返回200。
log.info(Integer.toString(result.getResponse().getStatusCode()));
if(result.getResponse().getStatusCode() != 200){
throw new GuiguException(ResultCodeEnum.FAIL);
}
//返回圖片路徑
//參考SDK中的:Java-> Java授權存取-> 生成以GET方法存取的簽名URL
// 設定URL過期時間為1小時,單位:毫秒
Date expiration = new Date(new Date().getTime() + 60 * 60 * 1000);
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
Map<String, String> map = new HashMap<>();
map.put("previewUrl", url.toString()); //頁面中授權預覽圖片
map.put("url", objectName); //資料庫儲存
return map;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
throw new GuiguException(ResultCodeEnum.FAIL, oe);
} catch (GuiguException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
throw new GuiguException(ResultCodeEnum.FAIL, ce);
} catch (IOException e) {
throw new GuiguException(ResultCodeEnum.FAIL, e);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
在service-util模組中新增AuthContextHolder.java
package com.atguigu.common.service.utils;
/**
* 授權校驗
*/
@Component
public class AuthContextHolder {
@Resource
private RedisTemplate redisTemplate;
/**
* 校驗token是否存在並返回UserId
* @param request
*/
public Long checkAuth(HttpServletRequest request){
//從http請求頭中獲取token
String token = request.getHeader("token");
if(StringUtils.isEmpty(token)) {
throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
}
Object userIdObj = redisTemplate.opsForValue().get("user:token:" + token);
//資料存入redis時,按照實際的大小分配空間,取出時int能存下,預設使用int型別,int存不下再用long
//我們無法判斷redis中儲存的是什麼型別的id,因此在此做一個轉換
Long userId = null;
if(userIdObj instanceof Integer){
userId = ((Integer)userIdObj).longValue();
}else if(userIdObj instanceof Long){
userId = (Long)userIdObj;
}else if(userIdObj instanceof String){
userId = Long.parseLong(userIdObj.toString());
}
if(StringUtils.isEmpty(userId)) {
throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
}
return userId;
}
}
新增校驗程式碼
...
public class FrontFileController {
...
@Resource
private AuthContextHolder authContextHolder;
...
public Result<Map<String, String>> upload(MultipartFile file, HttpServletRequest request) {
authContextHolder.checkAuth(request);
...
}
}
首先新增全域性引數token,然後再進行測試
建立FrontUserInfoController中新增如下方法
package com.atguigu.syt.user.controller.front;
@Api(tags = "使用者管理")
@RestController
@RequestMapping("/front/user/userInfo")
public class FrontUserInfoController {
@Resource
private UserInfoService userInfoService;
@Resource
private AuthContextHolder authContextHolder;
@ApiOperation(value = "使用者認證")
@ApiImplicitParam(name = "userAuthVo",value = "使用者實名認證物件", required = true)
@PostMapping("/auth/userAuth")
public Result userAuth(@RequestBody UserAuthVo userAuthVo, HttpServletRequest request) {
Long userId = authContextHolder.checkAuth(request);
userInfoService.userAuth(userId, userAuthVo);
return Result.ok();
}
}
介面:UserInfoService
/**
* 儲存實名認證資訊
* @param userId
* @param userAuthVo
*/
void userAuth(Long userId, UserAuthVo userAuthVo);
實現:UserInfoServiceImpl
@Override
public void userAuth(Long userId, UserAuthVo userAuthVo) {
//設定認證資訊
UserInfo userInfo = new UserInfo();
userInfo.setId(userId);
userInfo.setName(userAuthVo.getName());
userInfo.setCertificatesType(userAuthVo.getCertificatesType());
userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
//資訊更新
baseMapper.updateById(userInfo);
}
在service-user模組的FrontUserInfoController中新增如下方法
@ApiOperation(value = "獲取認證資訊")
@GetMapping("/auth/getUserInfo")
public Result<UserInfo> getUserInfo(HttpServletRequest request) {
Long userId = authContextHolder.checkAuth(request);
UserInfo userInfo = userInfoService.getUserInfoById(userId);
return Result.ok(userInfo);
}
主類新增
@EnableFeignClients("com.atguigu.syt")
介面:UserInfoService
/**
* 根據使用者id獲取使用者資訊
* @param userId
* @return
*/
UserInfo getUserInfoById(Long userId);
實現:UserInfoServiceImpl
@Override
public UserInfo getUserInfoById(Long userId) {
UserInfo userInfo = baseMapper.selectById(userId);
return this.packUserInfo(userInfo);
}
輔助方法:UserInfoServiceImpl
@Resource
private DictFeignClient dictFeignClient;
/**
* 封裝使用者狀態、認證狀態、證件型別資訊
* @param userInfo
* @return
*/
private UserInfo packUserInfo(UserInfo userInfo) {
String certificatesTypeString = dictFeignClient.getName(
DictTypeEnum.CERTIFICATES_TYPE.getDictTypeId(),
userInfo.getCertificatesType()
);
userInfo.getParam().put("certificatesTypeString", certificatesTypeString);
userInfo.getParam().put(
"authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus())
);
userInfo.getParam().put(
"statusString", UserStatusEnum.getStatusNameByStatus(userInfo.getStatus())
);
return userInfo;
}
InnerFileController類
package com.atguigu.syt.yun.controller.inner;
@Api(tags = "阿里雲檔案管理")
@RestController
@RequestMapping("/inner/yun/file")
public class InnerFileController {
@Resource
private FileService fileService;
@ApiOperation(value = "獲取圖片預覽Url")
@ApiImplicitParam(name = "objectName",value = "檔名", required = true)
@GetMapping("/getPreviewUrl")
public String getPreviewUrl(@RequestParam String objectName) {
return fileService.getPreviewUrl(objectName);
}
}
介面:FileService
/**
* 獲取圖片url地址
* @param objectName
* @return
*/
String getPreviewUrl(String objectName);
實現:FileServiceImpl
@Override
public String getPreviewUrl(String objectName) {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = ossConstantProperties.getEndpoint();
// 阿里雲賬號AccessKey擁有所有API的存取許可權,風險很高。強烈建議您建立並使用RAM使用者進行API存取或日常運維,請登入RAM控制檯建立RAM使用者。
String accessKeyId = ossConstantProperties.getKeyId();
String accessKeySecret = ossConstantProperties.getKeySecret();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = ossConstantProperties.getBucketName();
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 設定URL過期時間為1小時,單位:毫秒
Date expiration = new Date(new Date().getTime() + 60 * 60 * 1000);
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
System.out.println(url.toString());
return url.toString();
}
介面:
package com.atguigu.syt.yun.client;
@FeignClient(
value = "service-yun",
contextId = "fileFeignClient",
fallback = FileDegradeFeignClient.class
)
public interface FileFeignClient {
@GetMapping("inner/yun/file/getPreviewUrl")
String getPreviewUrl(@RequestParam String objectName);
}
降級:
package com.atguigu.syt.yun.client.impl;
@Component
public class FileDegradeFeignClient implements FileFeignClient {
@Override
public String getPreviewUrl(String objectName) {
return "圖片顯示失敗";
}
}
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service-yun-client</artifactId>
<version>1.0</version>
</dependency>
UserInfoServiceImpl:
@Resource
private FileFeignClient fileFeignClient;
UserInfoServiceImpl:packUserInfo方法中新增如下程式碼
String previewUrl = fileFeignClient.getPreviewUrl(userInfo.getCertificatesUrl());
userInfo.getParam().put("previewUrl", previewUrl);
注意:由於是遠端呼叫阿里雲伺服器,因此組態檔中feignClient的遠端超時時間可以設定的稍微長一些,避免個別情況下由於網路原因出現的圖片無法載入的情況
建立api/userInfo.js
import request from '@/utils/request'
//引入js-cookie
import cookie from 'js-cookie'
export default {
saveUserAuth(userAuth) {
return request({
url: `/front/user/userInfo/auth/userAuth`,
method: 'post',
data: userAuth,
headers:{token: cookie.get('token')}
})
},
getUserInfo() {
return request({
url: `/front/user/userInfo/auth/getUserInfo`,
method: `get`,
headers:{token: cookie.get('token')}
})
}
}
pages/user/index.vue檔案
資料:資料>實名認證>user
也可以統一傳送請求頭:刪除api/user.js 中對請求頭的設定,修改utils/request.js檔案如下
//引入js-cookie
import cookie from 'js-cookie'
修改請求攔截器
// http request 攔截器
service.interceptors.request.use(
config => {
//從cookie中取出token,並且在請求頭中攜帶token
if (cookie.get('token')) {
config.headers['token'] = cookie.get('token')
}
return config
},
err => {
return Promise.reject(err)
})
本文來自部落格園,作者:自律即自由-,轉載請註明原文連結:https://www.cnblogs.com/deyo/p/17479789.html