简体   繁体   中英

Getting refresh token from Microsoft Identity Platform

I have an Azure web app where I want users to sign into Microsoft (Azure AD). I need to get hold of the refresh token. I have already looked at examples which use libraries that refresh the token silently in the background, but for my design I need to get hold of the refresh token itself.

Is this possible to achieve with a high level authentication library (OpenID Connect?), and if so, how? For the manual approach, it is described here: https://docs.microsoft.com/en-us/graph/auth-v2-user Is there any example code or tutorial for this in ASP.NET or .NET Core?

Firstly i would suggest using MSAL which Maintains a token cache and refreshes tokens for you when they are close to expire. You don't need to handle token expiration on your own.

If you want to hold the refresh token , you can set the SaveTokens property to true when registering the OIDC middleware so that tokens will be saved into cookie . I assume you are using the Microsoft.AspNetCore.Authentication.AzureAD.UI library :

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";
    options.SaveTokens = true;


});

Then you can access the tokens in controller like :

var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
var idToken = await HttpContext.GetTokenAsync("id_token");

Update:

That is because you don't get refresh token correctly . For testing , you can use code flow and add offline_access scope of OIDC :

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";
    options.SaveTokens = true;
    options.ResponseType = "code";
    options.ClientSecret = "xxxxxx";
    options.Scope.Add("offline_access");
    options.TokenValidationParameters.ValidateIssuer = false;

});

Replace ClientSecret with the one you config in Azure portal .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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