该项目是一个最简化的 Spring Boot 应用程序,同时充当:
- Spring 授权服务器(通过
client_credentials流程颁发 JWT 访问令牌),以及 - 资源服务器(保护其自身的
/hello端点)。
它与 Spring 博客文章(2025年4月2日) 中展示的设置相对应。
# build & run
./mvnw spring-boot:run
# obtain a token
curl -u mcp-client:secret -d grant_type=client_credentials \
http://localhost:8081/oauth2/token | jq -r .access_token > token.txt
# call the protected endpoint
curl -H "Authorization: Bearer $(cat token.txt)" http://localhost:8081/hello你可以通过以下步骤测试 OAuth2 安全配置:
# This should return 401 Unauthorized, confirming OAuth2 security is active
curl -v http://localhost:8081/# Get and extract the full token response
curl -v -X POST http://localhost:8081/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: Basic bWNwLWNsaWVudDpzZWNyZXQ=" \
-d "grant_type=client_credentials&scope=mcp.access"
# Or to extract just the token (requires jq)
curl -s -X POST http://localhost:8081/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: Basic bWNwLWNsaWVudDpzZWNyZXQ=" \
-d "grant_type=client_credentials&scope=mcp.access" | jq -r .access_token > token.txt注意:Basic 认证头部的值是 bWNwLWNsaWVudDpzZWNyZXQ=) is the Base64 encoding of mcp-client:secret。
# Using the saved token
curl -H "Authorization: Bearer $(cat token.txt)" http://localhost:8081/hello
# Or directly with the token value
curl -H "Authorization: Bearer eyJra...token_value...xyz" http://localhost:8081/hello若响应成功并返回 "Hello from MCP OAuth2 Demo!",则说明 OAuth2 配置工作正常。
docker build -t mcp-oauth2-demo .
docker run -p 8081:8081 mcp-oauth2-demoaz containerapp up -n mcp-oauth2 \
-g demo-rg -l westeurope \
--image <your-registry>/mcp-oauth2-demo:latest \
--ingress external --target-port 8081入口 FQDN 将成为你的issuer(https://<fqdn>).
Azure provides a trusted TLS certificate automatically for *.azurecontainerapps.io)。
将以下入站策略添加到你的 API:
<inbound>
<validate-jwt header-name="Authorization">
<openid-config url="https://<fqdn>/.well-known/openid-configuration"/>
<audiences>
<audience>mcp-client</audience>
</audiences>
</validate-jwt>
<base/>
</inbound>APIM 会获取 JWKS 并验证每个请求。
免责声明:
本文件使用 AI 翻译服务 Co-op Translator 进行翻译。虽然我们力求准确,但请注意自动翻译可能存在错误或不准确之处。原始文件的母语版本应被视为权威来源。对于关键信息,建议采用专业人工翻译。对于因使用本翻译而产生的任何误解或误释,我们概不负责。