package com.vincent.rsf.openApi.controller.example;
|
|
import com.vincent.rsf.openApi.entity.constant.Constants;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.web.bind.annotation.*;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
/**
|
* API认证示例控制器
|
* 演示如何使用统一的认证机制(支持AppId/AppSecret和Token)
|
*/
|
@RestController
|
@RequestMapping("/api/example/auth")
|
public class ApiAuthExampleController {
|
private static final Logger log = LoggerFactory.getLogger(ApiAuthExampleController.class);
|
|
/**
|
* 获取受保护的数据 - 支持AppId/AppSecret或Token认证
|
*
|
* @param request HTTP请求
|
* @return 受保护的数据
|
*/
|
@GetMapping("/protected-data")
|
public Map<String, Object> getProtectedData(HttpServletRequest request) {
|
// 从请求属性中获取认证信息(由AppIdAuthenticationFilter设置)
|
String appId = (String) request.getAttribute(Constants.REQUEST_ATTR_APP_ID);
|
String userId = (String) request.getAttribute(Constants.REQUEST_ATTR_USER_ID);
|
|
log.info("访问受保护接口,AppId: {}, UserId: {}", appId, userId);
|
|
Map<String, Object> response = new HashMap<>();
|
response.put("code", "200");
|
response.put("message", "访问成功");
|
response.put("data", Map.of(
|
"appId", appId,
|
"userId", userId,
|
"protectedInfo", "这是受保护的数据",
|
"authType", userId != null ? "Token" : "AppId/AppSecret",
|
"timestamp", System.currentTimeMillis()
|
));
|
response.put("success", true);
|
|
return response;
|
}
|
|
/**
|
* 获取认证信息 - 支持AppId/AppSecret或Token认证
|
*
|
* @param request HTTP请求
|
* @return 认证信息
|
*/
|
@GetMapping("/auth-info")
|
public Map<String, Object> getAuthInfo(HttpServletRequest request) {
|
// 从请求属性中获取认证信息
|
String appId = (String) request.getAttribute(Constants.REQUEST_ATTR_APP_ID);
|
String userId = (String) request.getAttribute(Constants.REQUEST_ATTR_USER_ID);
|
|
log.info("获取认证信息,AppId: {}, UserId: {}", appId, userId);
|
|
Map<String, Object> response = new HashMap<>();
|
response.put("code", "200");
|
response.put("message", "获取认证信息成功");
|
response.put("data", Map.of(
|
"appId", appId,
|
"userId", userId,
|
"authType", userId != null ? "Token" : "AppId/AppSecret",
|
"authenticated", appId != null
|
));
|
response.put("success", true);
|
|
return response;
|
}
|
|
/**
|
* 测试接口 - 不需要认证
|
*
|
* @return 测试数据
|
*/
|
@GetMapping("/public-test")
|
public Map<String, Object> getPublicTest() {
|
Map<String, Object> response = new HashMap<>();
|
response.put("code", "200");
|
response.put("message", "公开接口访问成功");
|
response.put("data", Map.of(
|
"info", "这是一个不需要认证的公开接口",
|
"timestamp", System.currentTimeMillis()
|
));
|
response.put("success", true);
|
|
return response;
|
}
|
}
|