You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bot Framework中利用客户端ID和密钥从Cortana令牌获取用户详情?

Got it, let's walk through how to pull user details from that Cortana token in your Bot Framework bot—since you’ve already got the connected service set up and tokens flowing, this is straightforward once you break it down.

核心实现思路

  • Validate the token first: Cortana sends a JWT token, so your first step is to verify its signature, audience, and issuer to make sure it’s legitimate, unaltered, and intended for your app. You’ll use your registered client ID and secret here.
  • Extract basic user claims from the decoded token: JWTs include built-in claims like user ID, name, and email. You can decode the token to grab these without calling any external APIs.
  • Fetch detailed data via Microsoft Graph (optional): If you need richer user info (like department, office location, or manager), use the validated token as a Bearer token to call Microsoft Graph’s /me endpoint. Just make sure your app registration has the right permissions (e.g., User.Read) granted.

C# Example (Bot Framework SDK v4)

First, install these NuGet packages: System.IdentityModel.Tokens.Jwt, Microsoft.IdentityModel.Protocols.OpenIdConnect, Microsoft.Graph

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Graph;
using System.Threading.Tasks;

public async Task<User> RetrieveCortanaUserDetails(string cortanaToken, string clientId, string clientSecret)
{
    // 1. Set up token validation configuration
    var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
        "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",
        new OpenIdConnectConfigurationRetriever());
    
    var openIdConfig = await configManager.GetConfigurationAsync(default);
    
    var validationParams = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuers = openIdConfig.Issuer.Split(','),
        ValidateAudience = true,
        ValidAudience = clientId, // Your registered client ID
        ValidateLifetime = true,
        IssuerSigningKeys = openIdConfig.SigningKeys,
        ValidateIssuerSigningKey = true
    };

    // 2. Validate and decode the token
    var tokenHandler = new JwtSecurityTokenHandler();
    SecurityToken validatedToken;
    var claimsPrincipal = tokenHandler.ValidateToken(cortanaToken, validationParams, out validatedToken);
    
    // Pull basic info from claims
    var userId = claimsPrincipal.FindFirst("oid")?.Value;
    var userName = claimsPrincipal.FindFirst("name")?.Value;
    var userEmail = claimsPrincipal.FindFirst("email")?.Value;

    // 3. Call Microsoft Graph for detailed user data (optional)
    var graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(request =>
        {
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", cortanaToken);
            return Task.CompletedTask;
        }));
    
    var fullUserDetails = await graphClient.Me.Request().GetAsync();
    return fullUserDetails;
}

Node.js Example (Bot Framework SDK v4)

Install these dependencies first: jsonwebtoken, jwks-rsa, @microsoft/microsoft-graph-client, @azure/msal-node

const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const { Client } = require('@microsoft/microsoft-graph-client');
const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');
const { ClientSecretCredential } = require('@azure/msal-node');

async function getCortanaUserDetails(cortanaToken, clientId, clientSecret) {
    // 1. Validate the token's signature and claims
    const jwksClientInstance = jwksClient({
        jwksUri: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration/jwks'
    });

    const getSigningKey = (header, callback) => {
        jwksClientInstance.getSigningKey(header.kid, (err, key) => {
            const signingKey = key.publicKey || key.rsaPublicKey;
            callback(null, signingKey);
        });
    };

    const decodedToken = await new Promise((resolve, reject) => {
        jwt.verify(cortanaToken, getSigningKey, {
            audience: clientId,
            issuer: ['https://login.microsoftonline.com/common/v2.0'],
            algorithms: ['RS256']
        }, (err, decoded) => {
            if (err) reject(err);
            else resolve(decoded);
        });
    });

    // 2. Extract basic user info from decoded claims
    const userId = decodedToken.oid;
    const userName = decodedToken.name;
    const userEmail = decodedToken.email;

    // 3. Fetch detailed data via Microsoft Graph (optional)
    const credential = new ClientSecretCredential(
        'common',
        clientId,
        clientSecret
    );

    const authProvider = new TokenCredentialAuthenticationProvider(credential, {
        scopes: ['https://graph.microsoft.com/.default']
    });

    const graphClient = Client.initWithMiddleware({ authProvider });
    const fullUserDetails = await graphClient.api('/me').get();
    
    return fullUserDetails;
}

Quick Notes

  • Double-check that your Azure AD app registration has the required permissions (like User.Read) and that admin consent is granted if it’s an enterprise app.
  • JWT tokens expire, so handle token refresh logic if you need long-term access to user data.
  • The issuer value might vary based on your tenant; use common for multi-tenant scenarios (which works for Cortana).

内容的提问来源于stack exchange,提问作者user3527063

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:05:51