9

我有一个 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();
        }
    }
}

/启动.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 未授权

我觉得我真的很接近只是错过了一小部分,有人有什么想法吗?

4

2 回答 2

4

发布时间太长,但添加了有关如何在 github gist上进行设置的所有详细信息。

于 2014-01-03T15:24:33.983 回答
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 请求之前设置令牌。

于 2013-11-06T01:20:22.680 回答