ASP.NET Identity (with IdentityServer4) get external resource oauth access token

偶尔善良 提交于 2019-12-08 23:00:19

问题


I have been through the docs of identityServer4 and I have set it up to use Microsoft Office 365 as a login provider. When the user has logged in I want to make a button where he can allow my app to subscribe to his calendar events using the webhooks api of graph.microsoft.com

The code in startup.cs

app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
{
     AuthenticationScheme = "Microsoft",
     DisplayName = "Microsoft",
     SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,

     ClientId = "CLIENT ID",
     ClientSecret = "CLIENT SECRET",
     CallbackPath = new PathString("/signin-microsoft"),
     Events = new OAuthEvents
     {
         OnCreatingTicket = context =>
         {
             redisCache.Set("AccessToken", context.AccessToken.GetBytes(), new DistributedCacheEntryOptions
             {
                 AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(3)
             });
             return Task.FromResult(context);
         }
     }
     Scope =
     {
         "Calendars.Read",
         "Calendars.Read.Shared",
     },
     SaveTokens = true
});

But this is obviously not a viable path to go. I have only done this for testing purposes and to make a PoC of the subscriptions needed.

Now I would like to know if there is a smarter way to communicate with the identityServer that allows me to get this external access token, so that I can use the microsoft api on behalf of my logged in users?

Or is my only option to take the Microsoft AccessToken directly from this OAuthEvent and store it directly in a database, linked to the logged in user?

I really need this, since most of my functionality is based on data from third parties.


回答1:


Ok, so I finally got this working. I have created a new project that is using ASP.Net Identity and IdentityServer4 both build on top of ASP.Net Core.

The problem was that I wasn't completely aware of the flow that was used in the external login process.

If you use the boiler plates from both systems you will have an AccountController where the following method will be present:

//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    if (remoteError != null)
    {
        ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
        return View(nameof(Login));
    }
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        return RedirectToAction(nameof(Login));
    }

    // Sign in the user with this external login provider if the user already has a login.
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
    if (result.Succeeded)
    {
        await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

        _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
        return RedirectToLocal(returnUrl);
    }
    if (result.RequiresTwoFactor)
    {
        return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
    }
    if (result.IsLockedOut)
    {
        return View("Lockout");
    }
    else
    {
        // If the user does not have an account, then ask the user to create an account.
        ViewData["ReturnUrl"] = returnUrl;
        ViewData["LoginProvider"] = info.LoginProvider;
        var email = info.Principal.FindFirstValue(ClaimTypes.Email);
        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
    }
}

The important part here is the:

await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

This will save your external credentials in the database table associated with your ASP.Net identity. In the table AspNetUserTokens you will now have 3 entries, called something like: access_token, expires_at and token_type.

These are the tokens that we are interested in, that we can use to access the users credentials somewhere else in our application.

To fetch these tokens in the context of a logged in user:

var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(User, "Microsoft", "access_token");

And to fetch them for a user we fetch from the DB we can use:

var user = _userManager.Users.SingleOrDefault(x => x.Id == "myId");
if (user == null)
    return;

var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(claimsPrincipal, "Microsoft", "access_token");


来源:https://stackoverflow.com/questions/41040702/asp-net-identity-with-identityserver4-get-external-resource-oauth-access-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!