使用C#刷新MS Graph的身份验证令牌

时间:2016-12-13 10:47:25

标签: c# oauth dotnetopenauth microsoft-graph

如何刷新身份验证令牌 Microsoft Graph使用Microsoft Graph .NET Client Library或其他使用C#?

我目前正在做的是将令牌保留在静态类中:

public class TokenKeeper
{
    public static string token = null;
    public static string AcquireToken()
    {
        if (token == null || token.IsEmpty())
        {
            throw new Exception("Authorization Required.");
        }
        return token;
    }
    public static void Clear()
    {
        token = null;
    }
}

我在Startup类中填写了令牌:

public partial class Startup
{
    private static string AppKey = CloudConfigurationManager.GetSetting("ida:Password");
    private static string aadInstance = CloudConfigurationManager.GetSetting("ida:AADInstance");
    private static string TenantName = CloudConfigurationManager.GetSetting("ida:Tenant");
    private static string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, TenantName);
    private static string graphResourceId = CloudConfigurationManager.GetSetting("ida:GraphUrl");
    private BpContext db = new BpContext();

    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        string ClientId = CloudConfigurationManager.GetSetting("ida:ClientID");
        string Authority = "https://login.microsoftonline.com/common/";

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                Authority = Authority,
                Scope = "User.ReadBasic.All",
                //Details omitted
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        // Create a Client Credential Using an Application Key
                        ClientCredential credential = new ClientCredential(ClientId, AppKey);
                        string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                            "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);                    
                        TokenKeeper.token = result.AccessToken;

                        return Task.FromResult(0);
                    }
                     //Details omitted
                }
            });
    }
}

我也清除了退出时的令牌。

2 个答案:

答案 0 :(得分:1)

AuthenticationResult对象包含访问令牌和刷新令牌。因此,刷新令牌也可以在TokenKeeper中持久化,类似于访问令牌。当访问令牌到期时(由AuthenticationResult.ExpiresOn指示),使用带有AuthenticationContext.AcquireTokenByRefreshToken方法的刷新令牌来获取新的访问令牌。

如果您不想明确跟踪刷新令牌,请参阅ADAL Cache以了解ADAL库如何为您执行此操作。

答案 1 :(得分:0)

您可以通过提供与AccessToken一起收到的RefreshToken来刷新访问令牌。由于您的代码中有ID /机密,因此您可以使用它们来提供ClientCredential。 代码示例如下:

var authContext = new AuthenticationContext(“https://login.microsoftonline.com/common”);
var result = authContext.AcquireTokenByRefreshToken(refreshToken,new ClientCredential(ClientId,AppKey));