Reputation: 5078
I've got a IDP implemented in IdentityServer 4. My web app client(implemented in Mvc 5) authenticates with the IDP but now I need to get the access token from the request.
A way to do that in .Net Core is to use the Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions
like so:
HttpContext.Authentication.GetTokenAsync("acccess_token")
I would like to be able to do the same in my .net Mvc5 web app client but I can't find any nuget package or namespace that has a similar implementation. It is important to be able to do this in MVC5 and not .net Core. Anyone came across this before?
PS- Also worth to mention that I'm using OpenIdConnect
Upvotes: 18
Views: 18424
Reputation: 71
Inside OpenIdConnectAuthenticationNotifications events the AutenticationTicket and its claims ready (there is no need to call userinfo endpoint). In order to make that Ticket available (claimsprincipal) to the httpcontext.current.user do the following inside the SecurityTokenValidated event (ReplaceIdentity is just a custom extension method to replace the claims if exists an identity with same type):
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = (notification) =>
{
notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", notification.ProtocolMessage.AccessToken));
notification.OwinContext.Authentication.User.ReplaceIdentity(notification.AuthenticationTicket.Identity);
return Task.CompletedTask;
}
Achieve this result takes me three days of testing... but works excelent, you will have the User Identity available in HttpContext.Current.User with the other identities.
Upvotes: 3
Reputation: 4781
The recently released 4.1.0 version of Katana now supports the SaveTokens
property (backported from ASP.NET Core).
In order to get the access token:
SaveTokens
in your Startup class:app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Other options removed for readability
SaveTokens = true,
// Required for the authorization code flow to exchange for tokens automatically
RedeemCode = true
});
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];
Upvotes: 25