【问题标题】:How do you call an authenticated ServiceStack service once the client is authenticated using OAuth?使用 OAuth 对客户端进行身份验证后,如何调用经过身份验证的 ServiceStack 服务?
【发布时间】:2013-09-21 21:52:18
【问题描述】:

假设我有一个 Web 客户端(即 MVC 4 客户端),它使用 oAuth 提供程序(即 Facebook、Google 等)对用户进行身份验证。 我想在我的客户端逻辑中调用另一个 Web 服务,并且该 Web 服务还通过 oAuth 提供者进行身份验证。

来自客户端的 Web 服务请求是什么样的?我需要将什么传递给 Web 服务?

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    我建议您查看这个问题,How do I authorize access to ServiceStack resources using OAuth2 access tokens via DotNetOpenAuth?。海报提供了他的最终解决方案,包括一个示例解决方案的链接,他慷慨地开源了该解决方案。对于他的解决方案,客户端代码如下所示:

    // Create the ServiceStack API client and the request DTO
    var apiClient = new JsonServiceClient("http://api.mysite.com/");
    var apiRequestDto = new Shortlists { Name = "dylan" };
    
    // Wire up the ServiceStack client filter so that DotNetOpenAuth can 
    // add the authorization header before the request is sent
    // to the API server
    apiClient.LocalHttpWebRequestFilter = request => {
        // This is the magic line that makes all the client-side magic work :)
        ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text);
    }
    
    // Send the API request and dump the response to our output TextBox
    var helloResponseDto = apiClient.Get(apiRequestDto);
    
    Console.WriteLine(helloResponseDto.Result);
    

    此处提供了类似的解决方案:https://stackoverflow.com/a/13791078/149060,它演示了根据 OAuth 1.0a 进行的请求签名

    var client = new JsonServiceClient (baseUri);
    
    client.LocalHttpWebRequestFilter += (request) => {
        // compute signature using request and a previously obtained
        //  access token 
        string authorization_header = CalculateSignature (request, access_token);
    
        request.Headers.Add ("Authorization", authorization_header);
    };
    var response = client.Get<MySecuredResponse> ("/my/service");
    

    当然,您需要进行调整以适应您的 OAuth 提供者的要求,即签名、令牌等。

    【讨论】:

    • 感谢指点,但仍有两个细节难以解决。首先,如何获得上面提到的“access_token”(从哪里以及如何),其次如何“计算签名”,用什么算法/库。
    • 获取“access_token”以及如何“计算签名”将是特定于实现的。 ServiceStack includes support for some common OAuth and OAuth2 providers。如果不包括您选择的提供商,您必须查阅他们的文档并相应地实施。
    • 我明白了,所以没有通用的方法可以使用 ServiceStack 来执行此操作(对于任何提供商子集,例如 FaceBook、Twitter、Google),我听到你说的是什么吗?
    • 已预先构建了对 Twitter、Facebook 和 Yammer OAuth 的支持。还支持 Google、Yahoo、MyOpenId 和通用 OpenID。您是否阅读了我在之前评论中链接到的页面?
    • 我做到了,并且已经阅读了 Stackoverflow 和其他地方关于 ServiceStack 的所有其他帖子。我缺乏的是对 ServiceStack 如何进行授权的基本了解,或者我不相信对于似乎非常简单和常见的场景(即 MVC 4.0 与 ServiceStack Web 服务对话)没有可重用的库。我真正需要的是这个场景的完整示例,其中前端是一个独立的 MVC 应用程序,它调用一个安全且独立的 ServiceStack Web 服务,并且用户在 MVC 应用程序中进行了身份验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多