gpt4 book ai didi

javascript - OWIN 和 Forms Authentication with WEB API 2 with SPA

转载 作者:数据小太阳 更新时间:2023-10-29 03:52:06 37 4
gpt4 key购买 nike

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

Controller /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 是在浏览器上设置的:

ASPXAUTH040E3B4141C86457CC0C6A10781CA1EFFF1A32833563A6E7C0EF1D062ED9AF079811F1600F6573181B04FE3962F36CFF45F183378A3E23179E89D8D009C9E6783E366AF5E4EDEE39926A39E64C76B165

但登录后,进一步的请求将被视为未经授权...

状态码:401未授权

我觉得我真的很接近了,只是少了一小块,有人有什么想法吗?

最佳答案

您是否在您的应用中使用不记名 token ?如果您没有使用它而只想使用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 管道中删除承载身份验证中间件。

如果你想在你的应用中使用不记名 token ,你需要在浏览器中发送ajax请求之前设置 token 。

关于javascript - OWIN 和 Forms Authentication with WEB API 2 with SPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792261/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com