12

我正在实施 IdentityServer4 我正在制作 3 个不同的项目:

所有项目均使用 ASP.NET Core 创建,但 JS 客户端使用静态文件。

我需要 JS 客户端仅使用身份令牌(而不是访问令牌)与 API 连接,因为我只需要访问 API,不需要管理用户身份验证。

我正在阅读快速入门帖子https://identityserver4.readthedocs.io/en/dev/quickstarts/1_client_credentials.html

当我阅读时,我认为我需要使用隐式大类型,我不需要 OpenID Connect,只需要 OAuth2。

我也读了这篇文章 https://identityserver4.readthedocs.io/en/dev/quickstarts/7_javascript_client.html 但他们使用访问令牌,我不需要它,连接到我使用 oidc-client-js 库https ://github.com/IdentityModel/oidc-client-js我搜索了使用隐式大类型的方法,但我使用的方法将我重定向到http://localhost:5000/connect/authorize页面(我认为这是我需要使用 OpenID Connect 的时候)

实现这一目标的最佳方法是什么?我有什么错?如何使用 api 进行身份验证并调用http://localhost:5001/values

身份服务器项目

配置文件

public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",
                    ClientName = "JavaScript Client",
                    // no interactive user, use the clientid/secret for authentication
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,



                    RedirectUris = new List<string>
                    {
                        "http://localhost:5003/oidc-client-sample-callback.html"
                    },
                    AllowedCorsOrigins = new List<string>
                    {
                        "http://localhost:5003"
                    },

                    // scopes that client has access to
                    AllowedScopes = new List<string>
                    {
                        "api1"
                    }
                }
            };
        }

启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddDeveloperIdentityServer()
            .AddInMemoryScopes(Config.GetScopes())
            .AddInMemoryClients(Config.GetClients());
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(LogLevel.Debug);
        app.UseDeveloperExceptionPage();

        app.UseIdentityServer();
    }

API项目

启动.cs

public void ConfigureServices(IServiceCollection services)
{

    // Add framework services.
    services.AddMvc();

    services.AddSingleton<ITodoRepository, TodoRepository>();

    services.AddCors(options =>
    {
        // this defines a CORS policy called "default"
        options.AddPolicy("default", policy =>
        {
            policy.WithOrigins("http://localhost:5003")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
    });

    services.AddMvcCore()
        .AddAuthorization()
        .AddJsonFormatters();


}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseCors("default");

    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        ScopeName = "api1",

        RequireHttpsMetadata = false
    });

    app.UseMvc();

}

值控制器.cs

[Route("api/[controller]")]
    [Authorize]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value3" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
}

Javascript客户端项目

oidc-client-sample.html

<!DOCTYPE html>
<html>
<head>
    <title>oidc-client test</title>
    <link rel='stylesheet' href='app.css'>
</head>
<body>
    <div>
        <a href='/'>home</a>
        <a href='oidc-client-sample.html'>clear url</a>
        <label>
            follow links
            <input type="checkbox" id='links'>
        </label>
        <button id='signin'>signin</button>
        <button id='processSignin'>process signin response</button>
        <button id='signinDifferentCallback'>signin using different callback page</button>
        <button id='signout'>signout</button>
        <button id='processSignout'>process signout response</button>
    </div>

    <pre id='out'></pre>

    <script src='oidc-client.js'></script>
    <script src='log.js'></script>
    <script src='oidc-client-sample.js'></script>
</body>
</html>

oidc-client-sample.js

///////////////////////////////
// UI event handlers
///////////////////////////////
document.getElementById('signin').addEventListener("click", signin, false);
document.getElementById('processSignin').addEventListener("click", processSigninResponse, false);
document.getElementById('signinDifferentCallback').addEventListener("click", signinDifferentCallback, false);
document.getElementById('signout').addEventListener("click", signout, false);
document.getElementById('processSignout').addEventListener("click", processSignoutResponse, false);
document.getElementById('links').addEventListener('change', toggleLinks, false);

///////////////////////////////
// OidcClient config
///////////////////////////////
Oidc.Log.logger = console;
Oidc.Log.level = Oidc.Log.INFO;

var settings = {
    authority: 'http://localhost:5000/',
    client_id: 'client',
    redirect_uri: 'http://localhost:5003/oidc-client-sample-callback.html',
    response_type: 'token',
    scope: 'api1'
};
var client = new Oidc.OidcClient(settings);

///////////////////////////////
// functions for UI elements
///////////////////////////////
function signin() {
    client.createSigninRequest({ data: { bar: 15 } }).then(function (req) {
        log("signin request", req, "<a href='" + req.url + "'>go signin</a>");
        if (followLinks()) {
            window.location = req.url;
        }
    }).catch(function (err) {
        log(err);
    });
}
function api() {
    client.getUser().then(function (user) {
        var url = "http://localhost:5001/values";

        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.onload = function () {
            log(xhr.status, JSON.parse(xhr.responseText));
        }
        xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
        xhr.send();
    });
}

oidc-client-sample-callback.html

<!DOCTYPE html>
<html>
<head>
    <title>oidc-client test</title>
    <link rel='stylesheet' href='app.css'>
</head>
<body>
    <div>
        <a href="oidc-client-sample.html">back to sample</a>
    </div>
    <pre id='out'></pre>
    <script src='log.js'></script>
    <script src='oidc-client.js'></script>
    <script>
            Oidc.Log.logger = console;
            Oidc.Log.logLevel = Oidc.Log.INFO;
            new Oidc.OidcClient().processSigninResponse().then(function(response) {
                log("signin response success", response);
            }).catch(function(err) {
                log(err);
            });
    </script>
</body>
</html>
4

1 回答 1

3

据我所知,您的代码应该可以工作,它可以完成所有工作。

  1. 您的 JavaScript 应用程序 (localhost:5003) 请求一个令牌 ( function signin())。这将导致重定向到 IdentityServer
  2. IdentityServer (localhost:5000) 已设置并且客户端设置 (Client.cs) 与请求匹配。尽管缺少用户和资源的配置:请参见此处:https ://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/3_ImplicitFlowAuthentication/src/QuickstartIdentityServer/Startup.cs
  3. 您的 JavaScript 应用程序有一个正确的“登录页面”,即 IdentityServer 在成功登录后重定向回来的页面。此页面拾取新发行的令牌(new Oidc.OidcClient().processSigninResponse()
  4. xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);您的 JavaScript 应用程序会通过其 API 请求 ( )发送令牌
  5. 您的 API (localhost:5001) 设置正确,并将针对您的 IdentityServer 进行授权

所以我认为代码是正确的,但对术语有一些误解。

  • 你需要隐式授权。忘记 ClientCredentials,因为它是为另一个工作流设计的,不应该在浏览器中使用,因为客户端密码被暴露了。这意味着任何人都可以发行有效的令牌(“窃取”),您的安全性就会受到损害。(如果必须使用 ClientCredentials,请创建服务器代理方法)。
  • 您需要 OpenID Connect (OIDC) 和 OAuth2。(这些不是准确的定义!!)OIDC 为您颁发令牌(“将用户登录”),而 OAuth2 验证令牌。别担心,IdentityServer 会处理所有这些。
  • 您需要访问令牌。为请求者(您的 localhost:5003 JavaScript 应用程序)颁发身份令牌,访问令牌应“发送”到 API(您的 localhost:5001 API)
  • “登录”的重定向是正常的。这是 Web 应用程序的典型工作流程:您离开应用程序 (localhost:5003) 并最终进入 IdentityServer ( http://localhost:5000 )。成功登录后,您将被重定向回您的应用程序 (localhost:5003)
于 2017-11-07T08:41:58.720 回答