簡體   English   中英

存儲 owin oauth 不記名令牌

[英]Store owin oauth bearer token

我正在使用默認的 owin oauth 服務器創建一個簡單的身份驗證服務器。 提供正確的憑證后,會生成一個不記名令牌並將其返回給客戶端。 我使用了Taiseer的這個教程

我想在將令牌發送到客戶端之前將令牌存儲在數據庫中。 也許我完全忽略了它,但是在發送令牌之前我可以從哪里獲得令牌? 據我所知,令牌是在 GrantResourceOwnerCredentials 方法中驗證票證后生成的。 我猜令牌存儲在上下文中。 我怎樣才能把它弄出來?

啟動文件

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);
}

注意:對於那些想知道我為什么要存儲令牌的人..這是我必須滿足的要求。

要在將令牌發送到客戶端之前獲取令牌,您必須覆蓋TokenEndpointResponse

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

context對象有一個屬性AccessToken ,它將包含作為字符串的令牌表示。

在此處輸入圖片說明

OAuthTokenEndpointResponseContext包含一個對象字典
AdditionalResponseParameters IDictionary<string, object>允許我們找到該身份的所有聲明。

如果我們想獲取令牌的到期時間,我們會在字典中找到聲明.expires

context.AdditionalResponseParameters[".expires"]

如果有人有興趣玩客戶端和服務器交互的簡單集成,那么有一個 github存儲庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM