1
3 天以前 70ecc717c746eef0c4503a19031ada582f5e94d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package com.vincent.rsf.openApi.controller.example;
 
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.openApi.entity.constant.Constants;
import com.vincent.rsf.openApi.entity.dto.CommonResponse;
import com.vincent.rsf.openApi.entity.AppAuthParam;
import com.vincent.rsf.openApi.security.service.AppAuthService;
import com.vincent.rsf.openApi.security.utils.TokenUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
 
/**
 * Token认证示例控制器
 * 演示如何使用JWT Token进行接口保护
 */
@RestController
@RequestMapping("/api/example/token")
public class TokenAuthExampleController {
    private static final Logger log = LoggerFactory.getLogger(TokenAuthExampleController.class);
 
    @Resource
    private AppAuthService appAuthService;
 
    /**
     * 获取受保护的数据 - 需要有效的Token
     * 
     * @param request HTTP请求
     * @return 受保护的数据
     */
    @GetMapping("/protected-data")
    public Map<String, Object> getProtectedData(HttpServletRequest request) {
        // 从请求属性中获取认证信息(由TokenAuthenticationFilter设置)
        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", "这是受保护的数据",
            "timestamp", System.currentTimeMillis()
        ));
        response.put("success", true);
        
        return response;
    }
 
    /**
     * 获取用户信息 - 需要有效的Token
     * 
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/user-info")
    public Map<String, Object> getUserInfo(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,
            "userName", "用户" + (userId != null ? userId : "未知"),
            "role", "USER",
            "permissions", new String[]{"read", "write"}
        ));
        response.put("success", true);
        
        return response;
    }
 
    /**
     * 手动生成Token的示例接口
     * 注意:在实际应用中,这个接口通常需要其他形式的认证
     * 
     * @param appId 应用ID
     * @param userId 用户ID
     * @return 包含Token的响应
     */
    @PostMapping("/generate-token")
    public Map<String, Object> generateToken(@RequestParam String appId, @RequestParam(required = false) String userId) {
        log.info("生成Token,AppId: {}, UserId: {}", appId, userId);
        
        try {
            // 生成Token
            String token = TokenUtils.generateToken(appId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", "200");
            response.put("message", "Token生成成功");
            response.put("data", Map.of(
                "token", token,
                "appId", appId,
                "userId", userId,
                "expiresIn", 24 * 60 * 60 // 24小时过期
            ));
            response.put("success", true);
            
            return response;
        } catch (Exception e) {
            log.error("生成Token失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", "500");
            response.put("message", "生成Token失败: " + e.getMessage());
            response.put("data", null);
            response.put("success", false);
            
            return response;
        }
    }
 
 
 
    /**
     * 获取App认证Token
     *
     * @param param 应用ID和应用密钥
     * @return 认证Token
     */
    @ApiOperation("获取App认证Token")
    @PostMapping("/getToken")
    public CommonResponse getToken(@RequestBody AppAuthParam param) {
        String appId = param.getAppId();
        String appSecret = param.getAppSecret();
 
        if (Cools.isEmpty(appId, appSecret)) {
            return CommonResponse.error("AppId和AppSecret不能为空");
        }
 
        boolean isValid = appAuthService.validateApp(appId, appSecret);
        if (isValid) {
            String token = appAuthService.generateAppToken(appId, appSecret);
            return CommonResponse.ok()
                    .setMsg("获取Token成功")
                    .setData(token);
        } else {
            return CommonResponse.error("AppId或AppSecret无效");
        }
    }
 
//    /**
//     * 验证Token的接口
//     *
//     * @param token 要验证的Token
//     * @return Token验证结果
//     */
//    @PostMapping("/validateToken")
//    public Map<String, Object> validateToken(@RequestParam String token) {
//        log.info("验证Token: {}", token.substring(0, Math.min(10, token.length())) + "...");
//
//        boolean isValid = TokenUtils.validateToken(token);
//
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", "200");
//        response.put("message", isValid ? "Token有效" : "Token无效");
//        response.put("data", Map.of(
//                "valid", isValid,
//                "appId", isValid ? TokenUtils.getAppIdFromToken(token) : null,
//                "userId", isValid ? TokenUtils.getUserIdFromToken(token) : null
//        ));
//        response.put("success", isValid);
//
//        return response;
//    }
}