本文介绍了返回更多信息以使用OAuth承载令牌生成和Owin中的WebAPI客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我创建了一个的WebAPI和科尔多瓦的应用程序。
我使用的http请求的科尔多瓦应用程序和的WebAPI之间的通信。
在的WebAPI,我实现了OAuth的承载令牌生成。

I have created a WebApi and a Cordova application.I am using http requests to communicate between the Cordova application and the WebApi.In the WebApi, I've implemented OAuth Bearer Tokens 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);
    }

从科尔多瓦应用程序,我收到一个成功的登录请求API之后,下面的JSON

after a successful login request to the API from the Cordova app I receive the following JSON

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

的问题是,我需要关于用户的详细信息。例如,我有在数据库中UserGuid领域,我想将它发送到科尔多瓦应用程序时,登录成功,并在其他要求用到它。我可以包括其他信息返回给客户端,比其他的access_token,token_typeexpires_in ?如果没有,我怎么能得到基于API在用户的的access_token

The problem is, that I require more information about the user. For example I have a UserGuid field in the database and I want to send it to the Cordova app when the login is successful and to use it later in other requests. Can I include other information to return to the client, other than "access_token", "token_type" and "expires_in"? If not, how can I get the user in the API based on the access_token?

编辑:

我想我找到了一个解决方法。
我说里面 GrantResourceOwnerCredentials

I think that I found a workaround.I added the following code inside GrantResourceOwnerCredentials

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

和之后,我访问我的GUID像控制器这里面: User.Identity.Name

and after that I access the guid inside my controller like this: User.Identity.Name

我也可以添加的具有自定义名称的GUID identity.AddClaim(新索赔(GUID,user.UserGuid.ToString()));

I also can add the the guid with a custom name identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));

我还是很想知道,如果有更多的数据与承载令牌JSON返回给客户端的方式。

I'm still interested to know if there is a way to return more data to the client with the bearer token JSON.

推荐答案

您可以根据需要添加尽可能多的要求。结果
您可以从 System.Security.Claims 添加标准的索赔或创建自己的。结果
声称将在您的令牌加密,因此他们只会从资源服务器进行访问。

You can add as many claims as you want.
You can add the standard set of claims from System.Security.Claims or create your own.
Claims will be encrypted in your token so they will only be accessed from the resource server.

如果你希望你的客户端能够读取你的令牌的扩展属性,你有另一种选择: AuthenticationProperties

If you want your client to be able to read extended properties of your token you have another option: AuthenticationProperties.

比方说,你要添加的东西,使您的客户端可以访问。这是要走的路:

Let's say you want to add something so that your client can have access to. That's the way to go:

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

现在,您可以创建您在上面添加的属性票:

Now you can create a ticket with the properties you've added above:

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

这是你的客户端将获取结果:

That's the result your client will fetch:

.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控制器的资源服务器来读取它们:

On the other hand if you add claims you will be able to read them in your resource server in your API controller:

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

    return Ok();
}

ClaimsPrincipal 将包含新要求的的GUID ,你在这里补充说:

Your ClaimsPrincipal will contain your new claim's guid which you've added here:

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

如果您想了解更多关于owin,不记名令牌和网页API有一个很好的教程here这article将帮助您把握背后的概念的授权服务器资源服务器

If you want to know more about owin, bearer tokens and web api there's a really good tutorial here and this article will help you to grasp all the concepts behind Authorization Server and Resource Server.

更新

您可以在这里找到工作的例子。这是一个网页API + Owin 自托管。结果
有没有这里涉及到数据库。
客户端是一个控制台应用程序(有一个HTML + JavaScript的样本以及),它调用网页API传递的凭据。

You can find a working example here. This is a Web Api + Owin self-hosted.
There's no database involved here.The client is a console application (there's a html + JavaScript sample as well) which call a Web Api passing credentials.

由于Taiseer建议,你需要重写 TokenEndpoint

As Taiseer suggested, you need to override 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);
}

启用从解决方案多启动项目 - >属性,你可以运行它马上

这篇关于返回更多信息以使用OAuth承载令牌生成和Owin中的WebAPI客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:32