Files
IoT-OpenApi/src/main/java/com/iot/gateway/oauth/OAuth2TokenController.java
T

107 lines
5.1 KiB
Java

package com.iot.gateway.oauth;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iot.gateway.entity.OpenClient;
import com.iot.gateway.mapper.OpenClientMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@Tag(name = "OAuth 2.0 授权中心")
@RestController
@RequestMapping("/oauth2")
public class OAuth2TokenController {
@Autowired
private OpenClientMapper clientMapper;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Operation(summary = "客户端凭据模式换取访问令牌 (Client Credentials Grant)")
@PostMapping(value = "/token")
public ResponseEntity<Map<String, Object>> issueToken(
@RequestParam(value = "grant_type", required = false) String formGrantType,
@RequestParam(value = "client_id", required = false) String formClientId,
@RequestParam(value = "client_secret", required = false) String formClientSecret,
@RequestParam(value = "scope", required = false) String formScope,
@RequestBody(required = false) Map<String, String> jsonBody,
jakarta.servlet.http.HttpServletRequest request) {
String grantType = formGrantType != null ? formGrantType : (jsonBody != null ? jsonBody.get("grant_type") : null);
String clientId = formClientId != null ? formClientId : (jsonBody != null ? jsonBody.get("client_id") : null);
String clientSecret = formClientSecret != null ? formClientSecret : (jsonBody != null ? jsonBody.get("client_secret") : null);
String scope = formScope != null ? formScope : (jsonBody != null ? jsonBody.get("scope") : null);
Map<String, Object> error = new HashMap<>();
if (!"client_credentials".equalsIgnoreCase(grantType)) {
error.put("error", "unsupported_grant_type");
error.put("error_description", "仅支持 client_credentials 客户端凭据授权模式");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
if (clientId == null || clientSecret == null) {
error.put("error", "invalid_client");
error.put("error_description", "client_id 或 client_secret 不能为空");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error);
}
OpenClient client = clientMapper.selectOne(new LambdaQueryWrapper<OpenClient>()
.eq(OpenClient::getClientId, clientId));
if (client == null || !client.getClientSecret().equals(clientSecret)) {
error.put("error", "invalid_client");
error.put("error_description", "客户端标识或密钥错误");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error);
}
if (client.getStatus() == null || client.getStatus() != 1) {
error.put("error", "unauthorized_client");
error.put("error_description", "客户端已被禁用,无法申请令牌");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
}
if (client.getExpireTime() != null && client.getExpireTime().isBefore(LocalDateTime.now())) {
error.put("error", "expired_token");
error.put("error_description", "客户端凭证已过期");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
}
// 校验 IP 白名单
String clientIp = com.iot.gateway.common.IpUtils.getClientIp(request);
if (!com.iot.gateway.common.IpUtils.isAllowed(clientIp, client.getIpWhitelist())) {
log.warn("OAuth 2.0 客户端 IP 白名单拦截: clientId={}, clientIp={}, whitelist={}",
clientId, clientIp, client.getIpWhitelist());
error.put("error", "unauthorized_client");
error.put("error_description", "客户端来源 IP [" + clientIp + "] 不在允许的白名单范围内");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
}
String accessToken = jwtTokenProvider.generateToken(client);
log.info("OAuth 2.0 成功颁发令牌: clientId={}, clientIp={}, tenantId={}", clientId, clientIp, client.getTenantId());
Map<String, Object> response = new HashMap<>();
response.put("access_token", accessToken);
response.put("token_type", "Bearer");
response.put("expires_in", jwtTokenProvider.getTokenExpireSeconds());
response.put("scope", client.getScopes());
response.put("tenant_id", client.getTenantId());
response.put("client_name", client.getClientName());
return ResponseEntity.ok(response);
}
}