Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Startup.cs
- using System.Reflection;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- namespace App {
- public class Startup {
- private IConfiguration Configuration { get; }
- public Startup(IConfiguration configuration) {
- Configuration = configuration;
- }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services) {
- services.AddControllers();
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => {
- o.Authority = Configuration["Authority"];
- o.RequireHttpsMetadata = false;
- o.Audience = "api";
- o.SaveToken = true;
- });
- services.AddAuthorization();
- services.AddHttpContextAccessor();
- // Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
- // ...
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
- if(env.IsDevelopment() || env.IsEnvironment("Local")) {
- app.UseDeveloperExceptionPage();
- }
- else {
- app.UseHsts();
- }
- app.UseAuthentication();
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(x => {
- x.MapControllers();
- });
- }
- }
- }
- /// HttpClientExtensions.cs
- using System.Net.Http;
- using System.Net.Http.Headers;
- namespace App.Clients.Extensions {
- public static class HttpClientExtensions {
- internal static void InitHeaders(this HttpClient client, string token) {
- client.DefaultRequestHeaders.Clear();
- if(token != null) {
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
- }
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- }
- }
- }
- // SomeClient.cs
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Configuration;
- using App.Clients.Extensions;
- namespace App. Clients {
- public class SomeClient : HttpClient, ISomeClient{
- public SsoClient(IConfiguration config, IHttpContextAccessor http) {
- BaseAddress = new Uri(config["OpenId:Authority"]);
- var token = http.HttpContext.GetTokenAsync("access_token").Result;
- this.InitHeaders(token);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement