Guest User

Untitled

a guest
Jan 5th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 KB | None | 0 0
  1. ---------------------------------------------------------
  2. Startup.cs:
  3. ---------------------------------------------------------
  4. services.AddIdentityServer()
  5.                 .AddJwtBearerClientAuthentication()
  6.                 .AddDeveloperSigningCredential()
  7.                 .AddInMemoryPersistedGrants()
  8.                 .AddInMemoryIdentityResources(Config.GetIdentityResources())
  9.                 .AddInMemoryApiResources(Config.GetApiResources())
  10.                 .AddInMemoryClients(Config.GetClients())
  11.                 .AddAspNetIdentity<ApplicationUser>();
  12.  
  13.             services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddIdentityServerAuthentication(o =>
  14.             {
  15.                 o.Authority = "http://localhost:5000";
  16.                 o.RequireHttpsMetadata = false;
  17.                 o.ApiName = "api2";
  18.             });
  19.  
  20. ---------------------------------------------------------
  21. HomeController.cs
  22. ---------------------------------------------------------
  23. [Authorize(AuthenticationSchemes = "Bearer")]
  24.         public IActionResult Secured()
  25.         {
  26.             return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
  27.         }
  28.  
  29. ---------------------------------------------------------
  30. Wywołanie klienta z innej aplikacji MVC:
  31. ---------------------------------------------------------
  32. public async Task<IActionResult> ClientSecured()
  33.         {
  34.             var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
  35.             if (disco.IsError)
  36.             {
  37.                 return Content(disco.Error);
  38.             }
  39.  
  40.             var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
  41.             var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api2");
  42.             if (tokenResponse.IsError)
  43.             {
  44.                 return Content(tokenResponse.Error);
  45.             }
  46.  
  47.             HttpClient client = new HttpClient();
  48.             client.SetBearerToken(tokenResponse.AccessToken);
  49.             var response = await client.GetAsync("http://localhost:5000/home/secured");
  50.             if (!response.IsSuccessStatusCode)
  51.             {
  52.                 return Content("!response.IsSuccessStatusCode");
  53.             }
  54.  
  55.             var content = await response.Content.ReadAsStringAsync();
  56.             return Content(content);
  57.         }
Advertisement
Add Comment
Please, Sign In to add comment