我目前正在使用带有[授权]属性的ASP.net Web API。现在,我不是使用传统的方法,而是调用以下方法为我提供一个访问令牌,使用它可以访问Web API方法。
[System.Web.Http.HttpPost]
public object GetAccessToken(string Id, string UserName, string Email)
{
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, UserName));
oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Id));
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Email, Email));
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
DateTime currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
//ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));
ticket.Properties.ExpiresUtc = currentUtc.AddSeconds(20);
string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
Request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
JObject token = new JObject(
new JProperty("userName", UserName),
new JProperty("userId", Id),
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", currentUtc.AddSeconds(20).ToString()),
new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
new JProperty("expires", currentUtc.AddSeconds(20).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
);
return Ok(token);
}
注意:这很好用。
问题是任何人都可以通过简单的HTTPost请求访问此方法,并且因为它没有安全性而具有访问令牌。
直接提出问题:如何确保这种方法安全?