【发布时间】:2016-04-14 23:18:57
【问题描述】:
我在登录控制器中使用下面的代码将用户 JWT 访问令牌存储在响应 cookie 中
var returnedJwtToken = authenticationResponse.Content;
try
{
//Store a WebAPI JWT accesstoken in an FormsAuthenticationTicket userData
var ticket = new FormsAuthenticationTicket( 1,
login.UserName,
DateTime.Now,
DateTime.Now.Add(TimeSpan.FromSeconds(returnedJwtToken.ExpiresIn)),
login.RememberMe,
returnedJwtToken.AccessToken,
FormsAuthentication.DefaultUrl);
//Encrypt it
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
//Add it to Response.Cookies
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) {
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath,
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL };
Response.Cookies.Add(cookie);
然后我使用自定义的 MVC AuthorizeAttribute 来恢复访问令牌并将其放入请求标头中,以便可以在控制器上检索以将经过身份验证的请求发送到 WebAPI。它还为我的 MVC 应用程序控制器提供授权。
public class SiteAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// var tokenHandler = new JwtSecurityTokenHandler();
HttpCookie authCookie =httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
HttpContext.Current.Request.Headers["AccessKey"] = authTicket.UserData;
// Create the IIdentity instance
IIdentity id = new FormsIdentity(authTicket);
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, null);
// Set the context user
httpContext.User = principal;
}
var accessKey= httpContext.Request.Headers["AccessKey"];
return (!string.IsNullOrWhiteSpace(accessKey));
}
}
我还在帖子表单中使用 MVC ValidateAntiForgeryToken 过滤器来防止 CSRF 攻击。
我想知道这个解决方案是否足够安全?
如果是,我如何从令牌中检索角色和声明并在控制器上的授权过滤器中使用它们?
【问题讨论】:
-
将它存储在会话中怎么样?您提供给客户存储的任何内容都可以在发送之前进行修改。将它放在会话中,您仍然可以在服务器端访问它以传递给您的 WebAPI。
-
你的意思是我应该在会话中存储cookie吗?像这样:
Session.Add("AccessKey", cookie); -
不是整个 cookie,只是
returnedJwtToken.AccessToken。例如。Session.Add("AccessKey", returnedJwtToken.AccessToken) -
如何检索声明和角色?
-
使用FormsAuthenticationTicket有问题吗?我需要使用它的过期时间并记住我
标签: asp.net-mvc asp.net-web-api authorization access-token jwt