93 lines
3.2 KiB
C#
93 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Text.Encodings.Web;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace AuthSamples.VirtualScheme.PathSchemeSelection
|
|
{
|
|
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.AddMvc();
|
|
|
|
services.AddAuthentication("Dynamic")
|
|
.AddVirtualScheme("Dynamic", "Dynamic", o =>
|
|
{
|
|
o.DefaultSelector = ctx =>
|
|
{
|
|
return ctx.Request.Path.StartsWithSegments("/api") ? "Api" : CookieAuthenticationDefaults.AuthenticationScheme;
|
|
};
|
|
})
|
|
.AddScheme<AuthenticationSchemeOptions, ApiAuthHandler>("Api", o => { })
|
|
.AddCookie(options =>
|
|
{
|
|
options.AccessDeniedPath = "/account/denied";
|
|
options.LoginPath = "/account/login";
|
|
});
|
|
}
|
|
|
|
public class ApiAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
|
{
|
|
private readonly ClaimsPrincipal _id;
|
|
|
|
public ApiAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
|
|
{
|
|
var id = new ClaimsIdentity("Api");
|
|
id.AddClaim(new Claim(ClaimTypes.Name, "Hao", ClaimValueTypes.String, "Api"));
|
|
_id = new ClaimsPrincipal(id);
|
|
}
|
|
|
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
=> Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(_id, "Api")));
|
|
}
|
|
|
|
|
|
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
|
|
{
|
|
if (env.IsDevelopment())
|
|
{
|
|
app.UseDeveloperExceptionPage();
|
|
}
|
|
else
|
|
{
|
|
app.UseExceptionHandler("/Home/Error");
|
|
}
|
|
|
|
app.UseStaticFiles();
|
|
|
|
// Must go before UseMvc
|
|
app.UseAuthentication();
|
|
|
|
app.UseMvc(routes =>
|
|
{
|
|
routes.MapRoute(
|
|
name: "default",
|
|
template: "{controller=Home}/{action=Index}/{id?}");
|
|
routes.MapRoute(
|
|
name: "api",
|
|
template: "api/{controller=Home}/{action=Index}/{id?}");
|
|
});
|
|
}
|
|
}
|
|
}
|