存储owin oauth持票人令牌

时间:2015-10-16 15:34:18

标签: asp.net-web-api oauth owin

我正在使用默认的owin oauth服务器创建一个简单的身份验证服务器。在提供正确的凭证之后,生成承载令牌并将其返回给客户端。我使用了Taiseer的tutorial

我想在将令牌发送到客户端之前将令牌存储在数据库中。 也许我完全忽略了它,但在发送之前我可以在哪里获得令牌?据我所知,在GrantResourceOwnerCredentials方法中验证票证后生成令牌。 我猜这个令牌存储在上下文中。我怎么能把它拿出来?

Startup.cs

private void ConfigureAuthServer(IAppBuilder app) {
  // Configure the application for OAuth based flow
  var oAuthServerOptions = new OAuthAuthorizationServerOptions {
    //For Dev enviroment only (on production should be AllowInsecureHttp = false)
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/oauth/token"),
    Provider = new ApplicationOAuthProvider(),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
  };

  // Enable the application to use bearer tokens to authenticate users
  app.UseOAuthAuthorizationServer(oAuthServerOptions);
  app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

ApplicationOAuthProvider

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
  //Dummy check here
  if (context.UserName != context.Password) {
    context.SetError("invalid_grant", "The user name or password is incorrect");
    return Task.FromResult<object>(null);
  }

  var claims = new List<Claim> {
    new Claim(ClaimTypes.NameIdentifier, context.UserName),
    new Claim(ClaimTypes.Name, context.UserName)
  };

  var oAuthIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

  AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
  context.Validated(ticket);
  return Task.FromResult<object>(null);
}

public override Task TokenEndpoint(OAuthTokenEndpointContext context) {
  foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) {
    context.AdditionalResponseParameters.Add(property.Key, property.Value);
  }

  return Task.FromResult<object>(null);
}

注意:对于那些想知道我为什么要存储令牌的人来说......这是我必须履行的要求。

1 个答案:

答案 0 :(得分:11)

要在将令牌发送到客户端之前获取令牌,您必须覆盖TokenEndpointResponse

public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
    return base.TokenEndpointResponse(context);
}

context对象有一个属性AccessToken,它将包含令牌表示为字符串。

enter image description here