首页 文章

如何将IdentityServer4与带有ClientCredentials ASP.NET Core的Javascript客户端一起使用

提问于
浏览
9

我正在实现IdentityServer4,我正在制作3个不同的proyects:

所有项目都是使用ASP.NET Core创建的,但JS Client使用静态文件 .

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

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

在我阅读时,我认为我需要使用Implicit Grand Type,我不需要OpenID Connect,只需要OAuth2 .

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

实现这一目标的最佳方法是什么?我错了什么?我如何使用api进行认证并致电http://localhost:5001/values

IdentityServer Project

Config.cs

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"
                    }
                }
            };
        }

Startup.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 project

Startup.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();

}

ValuesController.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 client project

OIDC-客户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-客户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-客户采样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>

1 回答

  • 1

    据我所知,你的代码应该可行,它可以完成所有工作 .

    • 您的JavaScript应用程序(localhost:5003)请求令牌( function signin() ) . 这将导致重定向到IdentityServer

    • 已设置IdentityServer(localhost:5000),客户端设置(Client.cs)与请求匹配 . 虽然用户和资源缺少配置:请参阅此处:https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/3_ImplicitFlowAuthentication/src/QuickstartIdentityServer/Startup.cs

    • 您的JavaScript-app有一个正确的"landing page",这是一个页面,其中IdentityServer在成功登录后重定向回来 . 此页面获取新发布的令牌( new Oidc.OidcClient().processSigninResponse()

    • 您的JavaScript应用程序沿其API请求发送令牌( xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);

    • 您的API(localhost:5001)已正确设置并将针对您的IdentityServer进行授权

    所以我认为代码是正确的,但对这些条款存在一些误解 .

    • 您需要隐式授权 . 忘记ClientCredentials,因为它是为另一个工作流而设计的,不应在浏览器中使用,因为客户端密钥正在暴露 . 这意味着任何人都可以发出有效令牌("steal")并且您的安全性受到威胁 . (如果必须使用ClientCredentials,请创建服务器代理方法) .

    • 您需要OpenID Connect(OIDC)和OAuth2 . (这些不是准确的定义!!)OIDC为您发出令牌("logs the user in"),而OAuth2验证令牌 . 别担心,IdentityServer会照顾所有这些 .

    • 您需要访问令牌 . 为请求者(您的localhost:5003 JavaScript应用程序)发出身份令牌,访问令牌应该是"sent forward"到API(您的localhost:5001 API)

    • "login"的重定向是正常的 . 这是Web应用程序的典型工作流程:您将离开应用程序(localhost:5003)并最终进入IdentityServer(http://localhost:5000) . 成功登录后,您将被重定向回您的应用程序(localhost:5003)

相关问题