Search code examples
microsoft-graph-apiowinopenid-connect

Where does middleware save token?


I have a startup middleware written in vb.net. It successfully logs a user in and creates a claim for them. I am able to access the claim from a separate page in the application using the code below.

Dim claimsID As ClaimsIdentity = HttpContext.Current.User.Identity

What i can't figure out is how to also access the users token so that i can then use it for graph api calls.

This is the startup.vb

Imports Owin
Imports Microsoft.Owin
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Microsoft.Owin.Security.Notifications
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Identity.Client
Imports System.Threading.Tasks

<Assembly: OwinStartup(GetType(WEBCOMLogin.Startup))>
Namespace WEBCOMLogin
    Public Class Startup

        Private clientId As String = System.Configuration.ConfigurationManager.AppSettings("ClientId")
        Private redirectUri As String = System.Configuration.ConfigurationManager.AppSettings("RedirectUri")
        Shared tenant As String = System.Configuration.ConfigurationManager.AppSettings("Tenant")
        Private authority As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings("Authority"), tenant)

        Public Sub Configuration(ByVal app As IAppBuilder)
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
            app.UseCookieAuthentication(New CookieAuthenticationOptions())
            app.UseOpenIdConnectAuthentication(New OpenIdConnectAuthenticationOptions With {
                .clientId = clientId,
                .authority = authority,
                .redirectUri = redirectUri,
                .PostLogoutRedirectUri = redirectUri,
                .Scope = OpenIdConnectScope.OpenIdProfile,
                .ResponseType = OpenIdConnectResponseType.IdToken,
                .ResponseMode = OpenIdConnectResponseMode.FormPost,
                .SaveTokens = True,
                .RedeemCode = True,
                .tokenvalidationparameters = New tokenvalidationparameters With {
                    .ValidateIssuer = False
                },
                .Notifications = New OpenIdConnectAuthenticationNotifications With {
                    .AuthenticationFailed = AddressOf OnAuthenticationFailedAsync,
                    .AuthorizationCodeReceived = AddressOf OnAuthorizationCodeReceivedAsync
                }
            })
        End Sub

        Private Shared Function OnAuthenticationFailedAsync(ByVal notification As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
            notification.HandleResponse()
            Dim redirect As String = "owinerror.aspx?errormessage=" & notification.Exception.Message

            notification.Response.Redirect(redirect)
            Return Task.FromResult(0)
        End Function

        Private Async Function OnAuthorizationCodeReceivedAsync(ByVal notification As AuthorizationCodeReceivedNotification) As Task

            Dim idClient = ConfidentialClientApplicationBuilder.Create(clientId).WithTenantId(tenant).Build()

            Dim scopes As String = OpenIdConnectScope.OpenIdProfile
            Dim result = Await idClient.AcquireTokenByAuthorizationCode(scopes, notification.Code).ExecuteAsync()

            Dim userToken As String = result.AccessToken

        End Function

    End Class
End Namespace

Solution

  • By default when you set SaveTokens = True, , the OpenIDConnect will pass the tokens (id/access/refresh) to the cookie handler and the cookie handler will by default store them inside the session cookie.

    To later access the tokens you can in your controllers access them using:

    string accessToken = await HttpContext.GetTokenAsync("access_token");
    
    string idToken = await HttpContext.GetTokenAsync("id_token");
    
    string refreshToken = await HttpContext.GetTokenAsync("refresh_token");
    
    string tokenType = await HttpContext.GetTokenAsync("token_type");         
    
    string accessTokenExpire = await HttpContext.GetTokenAsync("expires_at");