[英]How to get Identity Server 4's access_token in ASP Net 4.7 MVC Application
我在ASP Net 4.7.2客戶端應用程序中獲取Identity Server 4的access_token來調用API時遇到一些問題。
在ASP .Net Core客戶端中,我可以這樣獲得access_token:
public async Task<IActionResult> CallApi()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("http://localhost:5001/identity");
ViewBag.Json = JArray.Parse(content).ToString();
return View("Json");
}
只是簡單的:
var accessToken = await HttpContext.GetTokenAsync("access_token");
但是,如何在ASP Net 4.x客戶端中獲取access_token?
我的啟動代碼如下所示:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var authority = JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieName = "CustomIdentityCookie"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
//AuthenticationType = "oidc",
Authority = "http://localhost:5000",
RedirectUri = "http://localhost:57319/signin-oidc",
PostLogoutRedirectUri = "http://localhost:57319/signout-callback-oidc",
ClientId = "mvc472",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = "api01 openid profile offline_access",
// for debug
RequireHttpsMetadata = false,
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies"
});
}
}
我有解決辦法。 希望任何人都可以告訴我該解決方案是否可以。 我使用了來自IdentityServer3的變通辦法,如下所示: IdentityServer 3 Mvc Client我編輯了描述的方法並更新到Identity Server 4。
除注銷外,它都有效:從Identity Server注銷后,我沒有重定向到MVC App。 我收到404錯誤,找不到/ signout-callback-oidc路由。
這里是新的Startup類:
public class Startup
{
public void Configuration(IAppBuilder app)
{
//var authority = JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
Authority = "http://localhost:5000",
RedirectUri = "http://localhost:57319/signin-oidc",
PostLogoutRedirectUri = "http://localhost:57319/signout-callback-oidc",
ClientId = "mvc472",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = "api01 openid profile offline_access",
// for debug
RequireHttpsMetadata = false,
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
var client = new HttpClient();
DiscoveryResponse disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
Address = disco.TokenEndpoint,
RedirectUri = "http://localhost:57319/signin-oidc",
ClientId = "mvc472",
ClientSecret = "secret",
Code = n.Code
});
var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
{
Address = disco.UserInfoEndpoint,
Token = tokenResponse.AccessToken
});
var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
id.AddClaims(userInfoResponse.Claims);
id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
id.AddClaim(new Claim("id_token", tokenResponse.IdentityToken));
id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));
n.AuthenticationTicket = new AuthenticationTicket(
new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
n.AuthenticationTicket.Properties
);
},
// noch nicht getestet
RedirectToIdentityProvider = n =>
{
// if signing out, add the id_token_hint
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
if (idTokenHint != null)
{
n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
}
}
return Task.FromResult(0);
}
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.