2016-09-28 32 views
9

Ben 3 diferents proyects yapıyorum bir IdentityServer4 uygulayan ediyorum:ile ve JavaScript istemci ClientCredentials ile IdentityServer4 nasıl kullanılır ASP.NET Çekirdek

Tüm proje ASP.NET Çekirdek ile oluşturulan, ancak JS Müşteri statik dosyaları kullanın edilmektedir.

Ben JS Müşteri yalnızca kimlik jetonu API ile bağlanmak Buna ihtiyacım (jeton erişemez) Ben sadece API erişimi olması gerekir, çünkü ben kullanıcı doğrulama yönetmesi gereken Yüklü. Ben kullanıcıya Örtülü Büyük Tipi ihtiyacım var ve OpenID Connect, sadece OAuth2 ihtiyacım yok olduğunu düşünün okurken ben Quickstarts okuyorum

https://identityserver4.readthedocs.io/en/dev/quickstarts/1_client_credentials.html

sonrası.

Ayrıca ben bu yazıyı https://identityserver4.readthedocs.io/en/dev/quickstarts/7_javascript_client.html okumak Ama belirteç erişimini kullanabilir ve ben kütüphane https://github.com/IdentityModel/oidc-client-js-js oidc-istemci kullanıyorum API bağlanmak ve Örtülü Büyük Tip ile kullanmak için bir yol aramak, o ihtiyacım yok ancak kullandığım yöntemler beni http://localhost:5000/connect/authorize sayfasına yönlendiriyor (OpenID Bağlantısını kullanmam gerektiğinde bunu düşünüyorum)

Bunu başarmanın en iyi yolu nedir? Neyi yanlış var? nasıl 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 projesi

API ile autenticate ve çağırabilir

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 istemci projesi

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- Numune 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-numune-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> 
+0

Neden API anonim hale getirilmiyor ve bir sürü iş kaydetmiyorsunuz? JavaScript'te İstemci Kimliği + İstemci Sırrı'nı kodlamanız gerekecek, bu da bunların tehlikeye düştüğü anlamına gelir; JavaScript'te sır saklamanızın bir yolu yoktur. – stevieg

+0

Evet, daha fazla okuyorum ve İhtiyacım Olan Büyük Tip https://aaronparecki.com/2012/07/29/2/oauth2-simplified adresine ihtiyacım var ancak doğru şekilde nasıl kullanılacağını bilmiyorum –

+0

IdentityServer4 herkese açık bir API'ye sahip Kullanmaya çalıştığım şeyi yaz. –

cevap

1

Bildiğim kadarıyla gördüğünüz gibi, kodunuz çalışması gerekir, her şeyi yapar.

  1. JavaScript-uygulamanız (localhost: 5003) bir belirteci (function signin()) ister. Bu, IdentityServer
  2. 'a yönlendirilir. IdentityServer (localhost: 5000) kuruldu ve istemci ayarları (Client.cs) isteğiyle eşleşiyor. Yapılandırma kullanıcılar ve kaynaklar için eksik olsa da: bkz: https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/3_ImplicitFlowAuthentication/src/QuickstartIdentityServer/Startup.cs
  3. JavaScript-uygulamanızın doğru bir "açılış sayfası" vardır, bir sayfa başarılı bir girişten sonra IdentityServer'ın yeniden yönlendirdiği bir sayfadır. doğru bir şekilde kurulmuş ve IdentityServer
  4. karşı yetkilendireceğiniz: Bu sayfa yeni verilmiş jetonu alır ( new Oidc.OidcClient().processSigninResponse())
  5. Sizin JavaScript Uygulamanın API isteği boyunca belirteç (xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);)
  6. API (5001 localhost) gönderir

Bu yüzden kodun doğru olduğunu düşünüyorum, ancak terimlerle ilgili bazı yanlış anlamalar var.

  • Implicit grant. İstemci sırrı açık olduğundan, başka bir iş akışı için tasarlandığından ve tarayıcıda kullanılmaması gerektiğinden, ClientCredentials'ı unutun. Bu, herkesin geçerli bir belirteç ("çalıntı") verebileceği ve güvenliğinizin tehlikeye girebileceği anlamına gelir. (,, ClientCredentials kullanıyorsa, bir sunucu proxy yöntemi oluşturun).
  • Hem OpenID Connect (OIDC) hem de OAuth2'ye ihtiyacınız vardır. (Bunlar doğru tanımlamalar değildir!) OIDC sizin için belirteç verir (OAuth2, belirtecini doğrular). Endişelenme, IdentityServer bunların hepsini halleder.
  • Erişim belirtecine ihtiyacınız var. İstek belirteci (localhost: 5003 JavaScript uygulamanız) için kimlik jetonu verilir, Erişim belirteci bir API'ye (localhost: 5001 API'niz) "ileri gönderilmelidir"
  • "Giriş" için yönlendirme normaldir. Bu, web uygulaması için tipik bir iş akışıdır: uygulamanızı bırakırsınız (localhost: 5003) ve IdentityServer'da (http://localhost:5000) sona erer. Başarılı giriş yaptıktan sonra uygulamanıza geri yönlendiriliyorsunuz (localhost: 5003)
İlgili konular