我有一个带有大量 javascript 调用的 Asp.Net MVC 应用程序。我保护了一个 MVC 操作,被重定向到身份服务器,登录,然后被重定向回客户端。我可以通过 MVC 进行后续调用,但是如何获取该访问令牌并在 ajax 调用中使用它?
这是我的 Startup.cs 文件:
public void Configuration(IAppBuilder app)
{
// Tell Microsoft to not try to map to .Net's ClaimsTypes
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
const string svcUrl = "https://localhost/svc.security";
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = svcUrl,
ClientId = "nedd_client",
RedirectUri = "http://localhost:61207/",
ResponseType = "code id_token token",
// Ask for 'roles' claims & for access to web services
Scope = "openid profile",
SignInAsAuthenticationType = "Cookies",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
// filter "protocol" claims
var claims = new List<Claim>(from c in n.AuthenticationTicket.Identity.Claims
where c.Type != "iss" &&
c.Type != "aud" &&
c.Type != "nbf" &&
c.Type != "exp" &&
c.Type != "iat" &&
c.Type != "nonce" &&
c.Type != "c_hash" &&
c.Type != "at_hash"
select c);
// Get userinfo data
var userInfoClient = new UserInfoClient(new Uri(svcUrl + "/connect/userinfo"), n.ProtocolMessage.AccessToken);
var userInfo = await userInfoClient.GetAsync();
userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2)));
// Get access token
var tokenClient = new OAuth2Client(new Uri(svcUrl + "/connect/token"), "nedd_client", "secret");
var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
claims.Add(new Claim("access_token", response.AccessToken));
claims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime().ToString()));
claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken));
n.AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(claims.Distinct(new ClaimComparer()), n.AuthenticationTicket.Identity.AuthenticationType), n.AuthenticationTicket.Properties);
},
}
});
}
这是一个示例 ajax 调用:
$.ajax({
type: 'GET',
url: "https://localhost/svc.security/connect/userinfo",
//headers: { "Authorization": "Bearer " + my.getAccessToken() }, // get access token from cookie?
}).done(function (data, textStatus, jqXHR) {
show(JSON.parse(jqXHR.response));