【问题标题】:web api 2 - Oauth2 Bearer token access is forbiddenweb api 2 - 禁止 Oauth2 Bearer 令牌访问
【发布时间】:2018-05-19 22:14:04
【问题描述】:

我有一个带有 web api 2 的 mvc 5 应用程序。(.NET 4.6) 我在我的 mvc 应用程序 (app.UseCookieAuthentication) 的身份验证旁边实现了 oauth2 配置:

    OAuthAuthorizationServerOptions OAuthServerOptions = new 
    OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/oauth/token"),
        Provider = new AspNetIdentityOAuthAuthorizationServerProvider(),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1000), 
    };

    app.UseOAuthBearerTokens(OAuthServerOptions);

我的 api 受到授权属性(全局过滤器)的保护。

我使用客户端凭据授权

我关注了这两篇文章(都是一样的) https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api https://mitchelsellers.com/blogs/2017/05/10/adding-webapi-oauth-authentication-to-an-existing-project

我能够为我的用户获取令牌,但是当我想使用令牌访问我的 Api 时,我收到了 403 禁止错误

        HttpClient client = new HttpClient();
        Dictionary<string, string> parameters = new Dictionary<string, string>();
        parameters.Add("grant_type", "client_credentials");
        parameters.Add("client_id", "4rclFahG7gho8erzbsmTbw==");
        parameters.Add("client_secret", "IBSqiYb0kT/lzV0gpQsPxkUDI9ztu0dhHWDe4VQDzKGYm2pl+75sMVfEsoGo4FAxFm0qZUFcDrVMrfqYhn2bzw==");

        var content = new FormUrlEncodedContent(parameters);
        try
        {
            HttpResponseMessage result = client.PostAsync("http://localhost:49594/oauth/token", content).Result;
            string jsonResult = result.Content.ReadAsStringAsync().Result;

            var resultObject = JsonConvert.DeserializeObject<TokenResult>(jsonResult);
            var accessToken = resultObject.access_token;


            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            result = client.GetAsync("http://localhost:49594/api/v1/echo?id=myt

estvalue").Result;

// RESULT  is 403 - Forbidden

我也用postman测试过,结果是一样的。

有人遇到过同样的问题吗?

你知道我错过了什么吗?

更新: 如果我将我的应用程序部署在服务器(azure 应用服务)上但仍然没有在我的机器上,它就可以工作

【问题讨论】:

    标签: oauth-2.0 asp.net-web-api2


    【解决方案1】:

    我找到了问题的原因!

    我正在为我的开发人员使用 stuntman (https://rimdev.io/stuntman/),但我忘记为 oauth 配置它...

    缺少这一行:

    StuntmanOptions.AllowBearerTokenPassthrough = true;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 2013-11-25
      • 2023-04-05
      相关资源
      最近更新 更多