Guest User

Untitled

a guest
Jan 14th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. public void ConfigureServices(IServiceCollection services) {
  2. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  3.  
  4. services.AddMvcCore().AddAuthorization().AddJsonFormatters();
  5.  
  6. services.AddAuthentication("Bearer")
  7. .AddIdentityServerAuthentication(options => {
  8. options.Authority = "http://localhost:5000"; //Identity Server URL
  9. options.RequireHttpsMetadata = false; // make it false since we are not using https
  10. options.ApiName = "Api_Name"; //api name which should be registered in IdentityServer
  11. });
  12. }
  13.  
  14. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  15. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  16. if (env.IsDevelopment()) {
  17. app.UseDeveloperExceptionPage();
  18. }
  19. else {
  20. app.UseHsts();
  21. }
  22.  
  23. app.UseAuthentication();
  24.  
  25. app.UseHttpsRedirection();
  26. app.UseMvc();
  27. }
  28.  
  29. var identityServer = await DiscoveryClient.GetAsync("http://localhost:5000"); //discover the IdentityServer
  30. if (identityServer.IsError) {
  31. Console.Write(identityServer.Error);
  32. return;
  33. }
  34.  
  35. HttpClient client = new HttpClient();
  36.  
  37. var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
  38. Address = identityServer.TokenEndpoint,
  39. ClientId = "Api_Client",
  40. ClientSecret = "secret",
  41.  
  42. UserName = "Majd",
  43. Password = "P@ssw0rd@123"
  44. });
  45.  
  46. if (tokenResponse.IsError) {
  47. Console.WriteLine(tokenResponse.Error);
  48. return;
  49. }
  50.  
  51. //Call the API
  52.  
  53. client.SetBearerToken(tokenResponse.AccessToken);
  54.  
  55. var response = await client.GetAsync("https://localhost:44368/api/values");
  56. var response2 = await client.GetAsync("https://localhost:44368/api/values/1");
  57. var content = await response.Content.ReadAsStringAsync();
  58. Console.WriteLine(JArray.Parse(content));
  59. Console.ReadKey();
Add Comment
Please, Sign In to add comment