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.
Ok, so I finally got this working. I have created a new project that is using
ASP.Net Identity
andIdentityServer4
both build on top ofASP.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: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 tableAspNetUserTokens
you will now have 3 entries, called something like:access_token
,expires_at
andtoken_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: