关于asp.net mvc:RestSharp使用Thinktecture AuthenticationConfiguration调用Web API

RestSharp calling WebAPI with Thinktecture AuthenticationConfiguration

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

MVC API设定

我的MVC API测试是通过以下方式设置的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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可以正常工作

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

1
2
3
4
5
6
7
8
9
10
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 Web前端客户端应用程序调用API-此请求的授权被拒绝

然后在我的MVC应用控制器动作中,我按如下方式使用RestSharp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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请求方法添加令牌,但是两种方式都拒绝相同的访问。

请问我在做什么错,或者在哪里看有什么建议?


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

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

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

在RestSharp中,您可以为标头AuthorizationAuthorization Session sometoken分配头

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

因此,我建议将您的RestSharp AddHeader代码更改为此:

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