Advertisement
electricmaster

API Bearer token

Mar 10th, 2021
960
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Startup.cs
  2.  
  3. using System.Reflection;
  4. using Microsoft.AspNetCore.Authentication.JwtBearer;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.EntityFrameworkCore;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Hosting;
  11.  
  12. namespace App {
  13.     public class Startup {
  14.        
  15.         private IConfiguration Configuration { get; }
  16.  
  17.         public Startup(IConfiguration configuration) {
  18.             Configuration = configuration;
  19.         }
  20.        
  21.         // This method gets called by the runtime. Use this method to add services to the container.
  22.         public void ConfigureServices(IServiceCollection services) {
  23.             services.AddControllers();
  24.             services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  25.                 .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => {
  26.                     o.Authority = Configuration["Authority"];
  27.                     o.RequireHttpsMetadata = false;
  28.                     o.Audience = "api";
  29.                     o.SaveToken = true;
  30.                     o.TokenValidationParameters = new TokenValidationParameters { // verbatim from SO :)
  31.                         IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tokenValidationParameters) =>
  32.                         {
  33.                             cache.TryGetValue("token");
  34.                         }
  35.                     };
  36.                 });
  37.             services.AddAuthorization();
  38.             services.AddHttpContextAccessor();
  39.  
  40.             // Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
  41.             // ...
  42.         }
  43.  
  44.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  45.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
  46.             if(env.IsDevelopment() || env.IsEnvironment("Local")) {
  47.                 app.UseDeveloperExceptionPage();
  48.             }
  49.             else {
  50.                 app.UseHsts();
  51.             }
  52.  
  53.            
  54.             app.UseAuthentication();
  55.             app.UseHttpsRedirection();
  56.             app.UseRouting();
  57.             app.UseAuthorization();
  58.             app.UseEndpoints(x => {
  59.                 x.MapControllers();
  60.             });
  61.         }
  62.     }
  63. }
  64.  
  65.  
  66. /// HttpClientExtensions.cs
  67.  
  68. using System.Net.Http;
  69. using System.Net.Http.Headers;
  70.  
  71. namespace App.Clients.Extensions {
  72.     public static class HttpClientExtensions {
  73.         internal static void InitHeaders(this HttpClient client, string token) {
  74.             client.DefaultRequestHeaders.Clear();
  75.  
  76.             if(token != null) {
  77.                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
  78.             }
  79.            
  80.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  81.         }
  82.     }
  83. }
  84.  
  85.  
  86. // SomeClient.cs
  87.  
  88. using System;
  89. using System.Collections.Generic;
  90. using System.Net.Http;
  91. using System.Text.Json;
  92. using System.Threading.Tasks;
  93. using Microsoft.AspNetCore.Authentication;
  94. using Microsoft.AspNetCore.Http;
  95. using Microsoft.Extensions.Configuration;
  96. using App.Clients.Extensions;
  97.  
  98. namespace App. Clients {
  99.     public class SomeClient : HttpClient, ISomeClient{
  100.         public SsoClient(IConfiguration config, IHttpContextAccessor http) {
  101.             BaseAddress = new Uri(config["OpenId:Authority"]);
  102.             var token = http.HttpContext.GetTokenAsync("access_token").Result;
  103.            
  104.             this.InitHeaders(token);
  105.         }
  106.     }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement