0

I'm Fetching access token in ASP.NET MVC application using Open ID connect hybrid flow. And using this access token to invoke Power BI Rest APIs. However once the access token has expired, the REST API calls fails for obvious reasons.

My question is How do I get the new access token/refresh without pushing user for interactive login?

  public void ConfigureAuth(IAppBuilder app)
    {
        try
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    RedirectUri = redirectUri,
                    UseTokenLifetime = false,
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = OnAuthorizationCodeCallback
                    }
                });

            app.UseStageMarker(PipelineStage.Authenticate);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    private static async Task OnAuthorizationCodeCallback(AuthorizationCodeReceivedNotification context)
    {
        var appConfidential = ConfidentialClientApplicationBuilder.Create(clientId)
                                             .WithRedirectUri(redirectUri)
                                             .WithClientSecret(clientSecret)
                                             .WithAuthority(authority)
                                             .Build();

        string powerBiPermissionApi = "https://analysis.windows.net/powerbi/api/";
        string[] ReadUserWorkspaces = new string[] {
            powerBiPermissionApi + "Workspace.Read.All",
            powerBiPermissionApi + "Report.Read.All",
            powerBiPermissionApi + "Dashboard.Read.All",
            powerBiPermissionApi + "Dataset.Read.All"
        };

        var authResult = await appConfidential.AcquireTokenByAuthorizationCode(ReadUserWorkspaces, context.Code).ExecuteAsync();
        ClaimsIdentity userClaims = context.AuthenticationTicket.Identity;
        userClaims.AddClaim(new Claim("Access_Token", authResult.AccessToken));
    }
PNDev
  • 590
  • 1
  • 8
  • 23
  • Are you able to get a refresh token? If so that's the recommended mechanism to do token renewal in a serverside application like this. – mackie Oct 20 '21 at 17:07

1 Answers1

0

With Azure Active Directory, we may specify our own custom timeout for measured days / Decouple the session length from the token validity.

One of the approaches I found is to separate the session duration from the original token's expiration times. By supplying the following option to the OIDC Middleware, you can tell it to stop controlling this aspect in the cookie Middleware:

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
 ... 
UseTokenLifetime = false, 
 }
 );

The cookie Middleware will now follow whatever settings you provide in the cookie Middleware parameters if UseTokenLifetime is set to false.

Alternatively, we can use an iFrame from a page that updates every 5 minutes.

<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" id="refreshAuthenticationIframe" src="@Url.Action("CheckSessionTimeout", "Home", new { area = "" })" style="display:none;"></iframe>

You find additional details through this Thread.

REFERENCES:

  1. Controlling a Web App’s session duration – CloudIdentity
  2. Solved: How to use Power BI Rest API without GUI authentic... - Microsoft Power BI Community
SwethaKandikonda
  • 7,513
  • 2
  • 4
  • 18