我有一个使用AngularJS构建的SPA应用程序,后端是WebApi2。我正在努力进行身份验证和授权。从长远来看,我想要的是启用针对Active Directory的身份验证。但就目前而言,我只是尝试为我的APiControllers启用授权并使用Owin设置Cookie。
这是我的Owin Identity Helper类,我只添加1个声明,即序列化的用户信息:
public void SignIn(bool rememberMe, T user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(user)),
};
var claimsIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = rememberMe }, claimsIdentity);
}
这是控制器中的身份验证:
[HttpGet, HttpPost]
[AllowAnonymous]
[Route("authenticate")]
public HttpResponseMessage Authenticate()
{
var authenticated = IdentityContext.Current.IsAuthenticated;
if (!authenticated)
{
var user = new User();
user.Email = "roger@moore.com";
user.Name = "Roger Moore";
user.Id = 23;
IdentityContext.Current.SignIn(true, user);
return new HttpResponseMessage()
{
Content = new StringContent(
JsonConvert.SerializeObject(user),
Encoding.UTF8,
"application/json"
)
};
}
else
{
//return the user if authenticated
return new HttpResponseMessage()
{
Content = new StringContent(
JsonConvert.SerializeObject(IdentityContext.Current.User), //from claim
Encoding.UTF8,
"application/json"
)
};
}
}
我的StartUp类
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/signedout")
});
}
}
当我调用身份验证用户时我正在设置登录,但是当使用[Authorize]属性调用控制器时,我没有登录。此外,当fiddler运行时我得到错误: “[Fiddler]响应标头解析失败。这可能是由于此次重用服务器套接字上的非法HTTP响应引起的 - 例如,非法包含正文的HTTP / 304响应。响应数据:”
是否有人对使用JWT令牌身份验证和从Angular到WebApi2的授权的示例代码有任何建议或替代方案?