ASP.NET Web API and OpenID Connect: how to get Access Token from Authorization Code

前端 未结 3 434
你的背包
你的背包 2021-02-04 04:57

I try to get OpenID Connect running... A user of my Web API managed to get an Authorization Code of a OpenID Connect Provider. How am I supposed to pass this code to my ASP.NET

3条回答
  •  佛祖请我去吃肉
    2021-02-04 05:39

    BenV already answered the question, but there's more to consider.

    class partial Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            // ...
    
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
              {
                ClientId = clientId,
                Authority = authority,
                Notifications = new OpenIdConnectAuthenticationNotifications() {
                    AuthorizationCodeReceived = (context) => {
                       string authorizationCode = context.Code;
                       // (tricky) the authorizationCode is available here to use, but...
                       return Task.FromResult(0);
                    }
                }
              }
        }
    }
    

    Two problems:

    • First of all, authorizationCode will get expired quickly. There's no sense in storing it.
    • The second problem is that AuthorizationCodeReceived event will not get fired for any of the page reloads as long as authorizationCode is not expired and stored inside the session.

    What you need to do is to call AcquireTokenByAuthorizationCodeAsync which will cache it and handle properly inside TokenCache.DefaultShare:

    AuthorizationCodeReceived = (context) => {
        string authorizationCode = context.Code;
        AuthenticationResult tokenResult = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, new Uri(redirectUri), credential);
        return Task.FromResult(0);
    }
    

    Now, before every call to the resource, invoke AcquireTokenSilentAsync to get the accessToken (it will use TokenCache or silently use refreshToken ). If token is expired, it will raise AdalSilentTokenAcquisitionException exception (invoke access code renew procedure).

    // currentUser for ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")
    AuthenticationResult authResult = await context.AcquireTokenSilentAsync(resourceUri, credential, currentUser);
    

    Calling AcquireTokenSilentAsync is very fast if token is cached.

提交回复
热议问题