RestSharp使用Thinktecture AuthenticationConfiguration调用WebAPI

时间:2014-12-23 22:22:34

标签: asp.net-mvc asp.net-web-api asp.net-web-api2 restsharp thinktecture-ident-model

我在MVC应用程序中使用Restsharp,尝试调用受Thinktecture IdentityModel AuthenticationConfiguration保护的后端MVC WebAPI。

MVC API设置

我的MVC API测试设置如下:

private static void ConfigureAuth(HttpConfiguration config)
{
    var authConfig = new AuthenticationConfiguration
    {
        DefaultAuthenticationScheme = "Basic",
        EnableSessionToken = true,
        SendWwwAuthenticateResponseHeader = true,
        RequireSsl = false,
        ClaimsAuthenticationManager = new AddCustomClaims(),

        SessionToken = new SessionTokenConfiguration
        {
            EndpointAddress = "/token",
            SigningKey = Convert.ToBase64String(CryptoRandom.CreateRandomKey(32)),
            DefaultTokenLifetime = new TimeSpan(1, 0, 0)
        }
    };

    authConfig.AddBasicAuthentication((username, password) =>
    {
        return username == "admin" && password == "password";
    });

    config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
}

private static void ConfigureCors(HttpConfiguration config)
{
    var corsConfig = new WebApiCorsConfiguration();
    config.MessageHandlers.Add(new CorsMessageHandler(corsConfig, config));

    corsConfig
        .ForAllOrigins()
        .AllowAllMethods()
        .AllowAllRequestHeaders(); 
}

Javascript正常运行

我知道100%我使用Restsharp发送的令牌是正确的并使用等效的json调用(javascript中使用的令牌与Web MVC控制器中使用的令牌相同,因为它存储在Session数组中):

var authToken = config.authToken,
baseUri = config.baseUri,
configureRequest = function (xhr) {
    xhr.setRequestHeader("Authorization", "Session " + authToken);
},
errorHandler = function (xhr, status, error) {
    if (xhr.status === 401 && config.onAuthFail) {
        config.onAuthFail(xhr, status, error);
    }
};

从我的MVC网络前端客户端应用程序调用API - 此请求已拒绝授权

然后在我的MVC app控制器操作中,我使用RestSharp,如下所示:

public ActionResult Test()
{
    var token = Session[Constants.SessionTokenKey] as string;

    var client = new RestClient(new Uri("http://localhost:65104/"));

    var request = new RestRequest("contacts", Method.GET);
    string authHeader = System.Net.HttpRequestHeader.Authorization.ToString();
    request.AddHeader(authHeader, string.Format("Authorization Session {0}", token));

    var json = client.Execute(request);
    // break point here checking the status it has been denied

    return View("Index");
}

检查状态,返回"{\"message\":\"Authorization has been denied for this request.\"}"

我尝试使用request.AddHeader(authHeader, string.Format("Authorization Session {0}", token));request.AddHeader(authHeader, string.Format("JWT {0}", token));的Restsharp请求方法添加令牌,但两种方式都获得相同的拒绝访问权限。

我做错了什么或者有关于去哪儿的建议?

1 个答案:

答案 0 :(得分:2)

您的JavaScript代码和RestSharp请求代码看起来不匹配。

在JS中,您设置名为Authorization的标头,并为其指定值Session sometoken

xhr.setRequestHeader("Authorization", "Session " + authToken);

在RestSharp中,您可以指定名称为Authorization的标头Authorization Session sometoken

request.AddHeader(authHeader, string.Format("Authorization Session {0}", token));

所以我建议您将RestSharp AddHeader代码更改为:

request.AddHeader(authHeader, string.Format("Session {0}", token));