我有一个由SPA JavaScript应用程序引用的Web API 2项目。
我正在使用OWIN对请求进行身份验证,并在使用Forms身份验证登录时,在每次发送回服务器时,我的资源在登录后都未经过身份验证。
App_Start / WebApiConfig.cs
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthBearerOptions.AuthenticationType));
config.EnableCors(new EnableCorsAttribute(
origins: "*", headers: "*", methods: "*"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
}
}
}
/Startup.cs
[assembly: OwinStartup(typeof(API.Startup))]
namespace API
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
App_Start / Startup.Auth.cs
namespace API
{
public partial class Startup
{
static Startup()
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
}
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
}
控制器/ AccountController.cs
namespace API.Controllers
{
public class AccountController : ApiController
{
public AccountController()
{
HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
}
[HttpPost]
[AllowAnonymous]
[Route("api/account/login")]
[EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
public HttpResponseMessage Login(LoginBindingModel login)
{
var authenticated = false;
if (authenticated || (login.UserName == "a" && login.Password == "a"))
{
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
var token = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = login.UserName,
AccessToken = token
}, Configuration.Formatters.JsonFormatter)
};
FormsAuthentication.SetAuthCookie(login.UserName, true);
return response;
}
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
[HttpGet]
[Route("api/account/profile")]
[Authorize]
public HttpResponseMessage Profile()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = User.Identity.Name
}, Configuration.Formatters.JsonFormatter)
};
}
}
}
然后我用JavaScript调用它:
$httpProvider.defaults.withCredentials = true;
login: function(user, success, error) {
return $http.post('/api/account/login', user);
},
profile:function(){
return $http.get('/api/account/profile');
}
我的Cookie已在浏览器中设置:
ASPXAUTH 040E3B4141C86457CC0C6A10781CA1EFFF1A32833563A6E7C0EF1D062ED9AF079811F1600F6573181B04FE3962F36CFF45F183378A3E23179E89D8D009C9E6783E366AF5E4EDEE39926A39E64C76B165
但登录后,进一步的请求被视为未经授权......
状态代码:401 Unauthorized
我觉得我真的很遗憾只是错过了一小块,有人有任何想法吗?
答案 0 :(得分:4)
您是否在使用应用中的Bearer令牌?如果您没有使用它并且只想使用cookie,请删除以下代码:
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthBearerOptions.AuthenticationType));
上面的代码只允许对web api进行承载身份验证。
您也可以删除app.UseOAuthBearerAuthentication(OAuthBearerOptions);
以从OWIN管道中删除承载身份验证中间件。
如果您想在应用中使用不记名令牌,则需要在浏览器中发送ajax请求之前设置令牌。
答案 1 :(得分:4)
发布时间太长,但添加了有关如何设置on github gist的所有详细信息。