【问题标题】:Authenticating WEB API 2 .net framework 4.x in identity server 4 using OIDC使用 OIDC 在身份服务器 4 中对 WEB API 2 .net framework 4.x 进行身份验证
【发布时间】:2018-11-15 05:31:07
【问题描述】:

我知道那里有类似的问题,但仍然不是很清楚, 在阅读了一堆与该主题相关的帖子后,这就是我“理解”代码的样子,我仍在处理 oauth/openid/owin/katana/identityserver 等涉及的所有概念......

大图是:我有一个角度应用程序, 在用户注册和登录的地方,不需要同意,一旦用户登录,SPA 将开始与后面的所有 api 通信,并且 api 应该能够针对身份验证服务器进行身份验证。

所以基本上,我需要我的 web api 能够通过客户端凭据授予类型在身份服务器 4 中进行身份验证,并使用身份验证服务器颁发的令牌。

我在身份服务器 4 中定义了这个客户端(web api 2 .net framework 4.5):

public static IEnumerable<Client> GetClients()
    {    
      //client credentials client
        return new List<Client>
        {
            new Client
        {  ClientId = "client2",
           AllowedGrantTypes = GrantTypes.ClientCredentials,

        ClientSecrets =
        {
            new Secret("secret".Sha256())
        },
           AllowedScopes = { "api2" }

        },

    }

在 .net Api 方面我有这个:

public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = 
                CookieAuthenticationDefaults.AuthenticationType
            });
            app.UseOpenIdConnectAuthentication(new 
            OpenIdConnectAuthenticationOptions
            {
                ClientId = "client2", 
                Authority = "http://localhost:5000",
                RequireHttpsMetadata = false,
                ResponseType = "id_token",
                Scope = "api2",
                SignInAsAuthenticationType = 
                CookieAuthenticationDefaults.AuthenticationType,
            }
        }); 

控制器使用 Autorize 装饰器进行装饰。 这些是我正在使用的软件包的版本

id="Microsoft.Owin.Security.OpenIdConnect" version="4.0.0"
id="Microsoft.Owin.Security.OAuth" version="4.0.0"
id="Microsoft.Owin.Security" version="4.0.0"
id="Microsoft.Owin" version="4.0.0"

当我使用来自官方项目站点 (https://github.com/IdentityServer/IdentityServer4.Samples) 的演示项目之一时,我在 MVC 演示应用程序中添加了一个额外的调用来调用我的 api。

public async Task<IActionResult> CallApiUsingUserAccessToken2()
    {
        var accessToken = await HttpContext.GetTokenAsync("access_token");
        var client = new HttpClient();
        client.SetBearerToken(accessToken);
        var content = await 
        client.GetStringAsync("http://localhost:17307/api
                               /Organization/GetOrganizationById/2007");
        ViewBag.Json = JArray.Parse(content).ToString();
        return View("Json");
    }

根据工作演示,有两种方法可以做到这一点,但没有一种对我有用。

public async Task<IActionResult> CallApiUsingClientCredentials2()
{
                var tokenClient = new TokenClient("http://localhost:5000/connect/token", "mvc", "secret");
                var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

                var client = new HttpClient();
                client.SetBearerToken(tokenResponse.AccessToken);
                var content = await client.GetStringAsync("http://localhost:17307/api/Organization/GetOrganizationById/2007");

                ViewBag.Json = JArray.Parse(content).ToString();
                return View("Json");
}

这是错误响应的一部分,我在两种情况下都会遇到:

<div class="row">
        <div class="col-sm-6">
            <div class="alert alert-danger">
                Sorry, there was an error

                    <strong>
                        <em>
                            : invalid_request
                        </em>
                    </strong>
                        <div>Invalid redirect_uri</div>
            </div>

                <div class="request-id">Request Id: 0HLIALF7L4N8J:00000001</div>
        </div>
    </div>

这里缺少什么或有什么问题,redirect_uri 是强制性的,为什么 .net 核心的配置部分中不存在?

这就是 .net core 中 api 的配置方式,并且工作正常。

public void ConfigureServices(IServiceCollection services)
{    
    services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.ApiName = "api1";
                });

}

提前致谢。

更新

经过一些试验,我确认我遇到的问题是在 api 中使用 owin 中间件验证访问令牌。

public void ConfigureAuth(IAppBuilder app)
{

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies",
    });

    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, 
    string> 
    ();

    app.UseIdentityServerBearerTokenAuthentication
    (new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        RequiredScopes = new[] { "api2" },
    });
}

我正在使用 identityserver3.accesstokenvalidation 执行验证,因为它被推荐,但是在客户端应用程序中获取访问令牌并将其传递给 api 请求后,我收到 401 未经授权的错误,这是因为它是期望在安全的 HTTPS 下运行?,我注意到 accesstokenvalidation v4 可以设置“RequireHttpsMetadata = false”,但我在 v3 中没有看到,这可能是我没有获得令牌验证的原因吗?

【问题讨论】:

    标签: identityserver4 openid-connect


    【解决方案1】:

    首先尝试在从“mvc”到“client2”的这一行中使用正确的client_id

    var tokenClient = new TokenClient("http://localhost:5000/connect/token", "mvc", "secret");

    【讨论】:

    • 你是对的,这是问题的一部分,现在我有了更多的理解,我意识到我在发布访问令牌时没有问题,我的问题在于 api 验证令牌.请看我的更新。谢谢
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2017-08-25
    • 2014-06-08
    相关资源
    最近更新 更多