12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.IdentityModel.Tokens;
- namespace AzureAuth
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // 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()
- .AddJwtBearer(options => //AzureADJwtBearer CN
- {
- //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
- options.Authority = "https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0";
- options.Audience = "72643704-b2e7-4b26-b881-bd5865e7a7a5";
- options.RequireHttpsMetadata = true;
- options.TokenValidationParameters = new TokenValidationParameters
- {
- RoleClaimType = "roles",
- ValidAudiences = new string[] { "72643704-b2e7-4b26-b881-bd5865e7a7a5", "api://72643704-b2e7-4b26-b881-bd5865e7a7a5" },
- };
- options.Events = new JwtBearerEvents();
- //下列事件有需要紀錄則打開
- //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
- //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
- //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
- options.Events.OnAuthenticationFailed = async context =>
- {
- await Task.FromResult(0);
- };
- options.Events.OnTokenValidated = async context =>
- {
- if (!context.Principal.Claims.Any(x => x.Type == "http://schemas.microsoft.com/identity/claims/scope") //ClaimConstants.Scope
- && !context.Principal.Claims.Any(y => y.Type == "roles")) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
- {
- //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
- throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
- }
- await Task.FromResult(0);
- };
- });
- }
- // 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())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
|