我有一個Asp.Net MVC應用程序與大量的JavaScript調用。我保護了MVC操作,重定向到身份服務器,登錄,然後重定向回客戶端。我可以通過MVC進行後續調用,但是如何獲取該訪問令牌並在ajax調用中使用它?如何通過javascript與IdentityServer3傳遞我的訪問令牌?
這是我的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));
難道你不能只存儲在Web瀏覽器上的本地存儲訪問令牌?訪問令牌不需要保密。如果它被篡改的話,它會被阻止被接受。 – webworm