我正在.NET Web应用程序中实现Web API 2服务体系结构.消费请求的客户端是纯javascript,没有mvc/asp.net.我正在使用OWIN尝试根据本文使用Web API示例进行OWIN Bearer Token身份验证来启用令牌身份验证.在获得授权后,我似乎遗漏了认证步骤.
我的登录信息如下:
[HttpPost]
[AllowAnonymous]
[Route("api/account/login")]
public HttpResponseMessage Login(LoginBindingModel login)
{
// todo: add auth
if (login.UserName == "a@a.com" && 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));
DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = login.UserName,
AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
}, …Run Code Online (Sandbox Code Playgroud) Web API 2 OWIN承载令牌认证 - AccessTokenFormat null?
默认/令牌端点工作正常,我可以从那里获得令牌,但我需要在票证上使用AccessTokenFormat.Protect方法为externalLogin生成accessToken.
基本上我的实现与这个实现几乎相同,我遇到了同样的问题,即AccessTokenFormat为null.从文档中可以看出:
用于保护访问令牌中包含的信息的数据格式.如果应用程序未提供,则默认数据保护提供程序取决于主机服务器.IIS上的SystemWeb主机将使用ASP.NET机器密钥数据保护,而HttpListener和其他自托管服务器将使用DPAPI数据保护.如果分配了不同的访问令牌提供程序或格式,则必须将兼容的实例分配给资源服务器的OAuthBearerAuthenticationOptions.AccessTokenProvider或OAuthBearerAuthenticationOptions.AccessTokenFormat属性.
在我看来,如果未分配AccessTokenFormat,主机将为其提供基本实现.但我不认为它在这里有效.有没有办法找到ISecureDataFormatAccessTokenFormat的默认实现并手动将其分配给变量?
或者有没有人有其他想法如何解决这个问题?
更新:我获取katana的源代码并找到OAuthAuthorizationServerMiddleware类,从源代码我可以看到以下代码:
if (Options.AccessTokenFormat == null)
{
IDataProtector dataProtecter = app.CreateDataProtector(
typeof(OAuthAuthorizationServerMiddleware).Namespace,
"Access_Token", "v1");
Options.AccessTokenFormat = new TicketDataFormat(dataProtecter);
}
Run Code Online (Sandbox Code Playgroud)
在我的Startup.Auth中,这是我的代码:
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
OAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/Token"),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat;
OAuthBearerOptions.AccessTokenProvider …Run Code Online (Sandbox Code Playgroud)