feat: 统一开放接口网关微服务初始化工程 (OAuth2.0 + MCP + OpenAPI + Webhook)
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package com.iot.gateway.oauth;
|
||||
|
||||
import com.iot.gateway.entity.OpenClient;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
|
||||
@Value("${gateway.oauth.jwt-secret:iot-gateway-oauth2-super-secret-key-666888-abcdefghijklmnopqrstuvwxyz}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Value("${gateway.oauth.token-expire-seconds:7200}")
|
||||
private long tokenExpireSeconds;
|
||||
|
||||
private Key getSigningKey() {
|
||||
return Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateToken(OpenClient client) {
|
||||
long nowMillis = System.currentTimeMillis();
|
||||
Date now = new Date(nowMillis);
|
||||
Date exp = new Date(nowMillis + tokenExpireSeconds * 1000);
|
||||
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("tenant_id", client.getTenantId());
|
||||
claims.put("client_name", client.getClientName());
|
||||
claims.put("scopes", client.getScopes());
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(client.getClientId())
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(exp)
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parseToken(String token) {
|
||||
try {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(getSigningKey())
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
} catch (Exception e) {
|
||||
log.warn("JWT 令牌解析或验签失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
if (claims == null) return false;
|
||||
return claims.getExpiration().after(new Date());
|
||||
}
|
||||
|
||||
public long getTokenExpireSeconds() {
|
||||
return tokenExpireSeconds;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user