简体   繁体   English

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

[英]Refresh auth token for MS Graph with C#

How to refresh Authentication token for Microsoft Graph using Microsoft Graph .NET Client Library or other using C#? 如何使用Microsoft Graph .NET客户端库或其他使用C#刷新Microsoft Graph的身份验证令牌?

What I am currently doing is keeping token in the static class: 我目前正在做的是将令牌保留在静态类中:

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;
    }
}

I fill in the token in Startup class: 我在启动类中填写令牌:

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
                }
            });
    }
}

I also clear the token on Sign Out. 我还会在“退出”上清除令牌。

The AuthenticationResult object contains both access token and refresh token. AuthenticationResult对象包含访问令牌和刷新令牌。 So, the refresh token can also be persisted in TokenKeeper similar to access token. 因此,刷新令牌也可以类似于访问令牌一样保存在TokenKeeper中。 When access token expires (indicated by AuthenticationResult.ExpiresOn), use the refresh token with AuthenticationContext.AcquireTokenByRefreshToken method to get new access token. 当访问令牌过期时(由AuthenticationResult.ExpiresOn指示),将刷新令牌与AuthenticationContext.AcquireTokenByRefreshToken方法一起使用以获取新的访问令牌。

If you don't want to track refresh tokens explicitly, please refer to ADAL Cache to know how ADAL library can do it for you. 如果您不想明确跟踪刷新令牌,请参考ADAL缓存以了解ADAL库如何为您完成此任务。

You can refresh access token by providing RefreshToken which you received alongside AccessToken. 您可以通过提供随AccessToken一起收到的RefreshToken来刷新访问令牌。 Since you have ID/Secret available in you code you can use them to provide ClientCredential. 由于您的代码中有可用的ID /秘密,因此可以使用它们提供ClientCredential。 Code example would be: 代码示例为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM