簡體   English   中英

使用 WebApi 中的 OAuth Bearer Tokens Generation 和 Owin 向客戶端返回更多信息

[英]Return more info to the client using OAuth Bearer Tokens Generation and Owin in WebApi

我創建了一個 WebApi 和一個 Cordova 應用程序。 我正在使用 HTTP 請求在 Cordova 應用程序和 WebAPI 之間進行通信。 在 WebAPI 中,我實現了 OAuth Bearer Token Generation。

public void ConfigureOAuth(IAppBuilder app)
    {
        var oAuthServerOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider(new UserService(new Repository<User>(new RabbitApiObjectContext()), new EncryptionService()))
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(oAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }

這是在SimpleAuthorizationServerProvider實現中

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
       context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        // A little hack. context.UserName contains the email
        var user = await _userService.GetUserByEmailAndPassword(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "Wrong email or password.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }

從 Cordova 應用程序成功登錄 API 請求后,我收到以下 JSON

{"access_token":"some token","token_type":"bearer","expires_in":86399}

問題是,我需要有關用戶的更多信息。 例如,我在數據庫中有一個 UserGuid 字段,我想在登錄成功時將其發送到 Cordova 應用程序,並稍后在其他請求中使用它。 除了"access_token", "token_type""expires_in"之外,我是否可以包含其他信息以返回給客戶端? 如果沒有,我如何根據access_token在 API 中獲取用戶?


編輯:

我想我找到了解決方法。 我在GrantResourceOwnerCredentials添加了以下代碼

identity.AddClaim(new Claim(ClaimTypes.Name, user.UserGuid.ToString()));

之后,我像這樣訪問控制器內的 GUID: User.Identity.Name

我還可以添加具有自定義名稱identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));

我仍然很想知道是否有辦法使用承載令牌 JSON 向客戶端返回更多數據。

您可以根據需要添加任意數量的聲明。
您可以從System.Security.Claims添加標准聲明集或創建自己的聲明集。
聲明將在您的令牌中加密,因此只能從資源服務器訪問它們。

如果您希望客戶端能夠讀取令牌的擴展屬性,則可以使用另一個選項: AuthenticationProperties

假設您要添加一些內容,以便您的客戶可以訪問。 這是要走的路:

var props = new AuthenticationProperties(new Dictionary<string, string>
{
    { 
        "surname", "Smith"
    },
    { 
        "age", "20"
    },
    { 
    "gender", "Male"
    }
});

現在,您可以使用上面添加的屬性創建故障單:

var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);

這是您的客戶將獲取的結果:

.expires: "Tue, 14 Oct 2014 20:42:52 GMT"
.issued: "Tue, 14 Oct 2014 20:12:52 GMT"
access_token: "blahblahblah"
expires_in: 1799
age: "20"
gender: "Male"
surname: "Smith"
token_type: "bearer"

另一方面,如果添加聲明,您將能夠在API控制器的資源服務器中讀取它們:

public IHttpActionResult Get()
{
    ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

    return Ok();
}

您的ClaimsPrincipal將包含您在此處添加的新聲明的guid

identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));

如果您想了解更多關於owin,承載令牌和網絡API有一個很好的教程在這里 ,這文章將幫助您掌握的背后授權服務器資源服務器的所有概念。

更新

你可以在這里找到一個有效的例子。 這是一個Web Api + Owin自托管。
這里沒有涉及數據庫。 客戶端是一個控制台應用程序(也有一個html + JavaScript示例),它調用Web Api傳遞憑據。

正如Taiseer建議的那樣,你需要覆蓋TokenEndpoint

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

從解決方案 - >屬性啟用“多個啟動項目”,您可以立即運行它。

如果不需要,我建議不要在令牌上添加額外的聲明,因為會增加令牌的大小,並且您將繼續發送每個請求。 由於LeftyX建議將它們添加為屬性,但請確保在成功獲取令牌時覆蓋TokenEndPoint方法以將這些屬性作為響應,沒有此終點,屬性將不會在響應中返回。

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

您可以在此處查看我的回購以獲取完整示例。 希望它會有所幫助。

GrantResourceOwnerCredentials函數中,您可以使用以下行向響應添加更多信息。

ticket.Properties.Dictionary.Add(new KeyValuePair<string, string>("Tag", "Data")); // Or whatever data you want to add

暫無
暫無

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

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