[英]ASP .NET Core 2.0 - JWT External Auth
I am trying to get started with authentication on an ASP.NET Core 2.0 web app. 我正在尝试开始在ASP.NET Core 2.0 Web应用程序上进行身份验证。
My company is using Ping Federate and I am trying to authenticate my users using the company login page and in return validating the returned token using my signing key ( X509SecurityKey
down here). 我的公司正在使用Ping Federate,我正在尝试使用公司登录页面对用户进行身份验证,并使用我的签名密钥(此处为X509SecurityKey
来验证返回的令牌。
The login page link looks like: 登录页面链接如下所示:
https://companyname.com/authorization.oauth2?response_type=code&redirect_uri=https%3a%2f%2fJWTAuthExample%2fAccount%2fLogin&client_id=CompanyName.Web.JWTAuthExample&scope=&state=<...state...>
Out of the box, I configured the Startup.cs to be able to log in and challenge against this site. 开箱即用,我将Startup.cs配置为能够登录并挑战该站点。
I decorated my HomeController with a [Authorize(Policy="Mvc")]
but when I access one of the pages, I just get a blank page. 我用[Authorize(Policy="Mvc")]
装饰了HomeController,但是当我访问其中一个页面时,我只会得到一个空白页面。
Debug is not hitting the OnChallenge
or OnAuthenticationFailed
methods when I add it to options.Events
(I think because user needs to be authenticated first). 当我将Debug添加到options.Events
时,它没有击中OnChallenge
或OnAuthenticationFailed
方法(我认为是因为首先需要对用户进行身份验证)。
So, what am I missing in order for a redirect to my authentication website to happen? 因此,为了重定向到身份验证网站,我缺少什么? Is it built in or do I have to do some manual configuration? 它是内置的还是必须进行一些手动配置?
(Note: In other web apps, using asp net framework, I use a redirect in an Authorize attribute when authentication fails) (注意:在其他Web应用程序中,使用asp net框架,当身份验证失败时,我会在Authorize属性中使用重定向)
Related post: Authorize attribute does not redirect to Login page when using .NET Core 2's AddJwtBearer - From this post, does it mean I am not using the right authentication method? 相关文章: 使用.NET Core 2的AddJwtBearer时,Authorize属性不会重定向到“登录”页面 -从这篇文章中,这意味着我没有使用正确的身份验证方法吗? I am building a web app, not an API. 我正在构建一个Web应用程序,而不是API。
namespace JWTAuthExample
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
string certificatepath = Path.Combine(HostingEnvironment.ContentRootPath, $"App_Data\\key.cer");
KEY = new X509SecurityKey(new X509Certificate2(certificatepath));
}
public IConfiguration Configuration { get; }
public IHostingEnvironment HostingEnvironment { get; }
private string AUTH_LOGINPATH { get; } = Configuration["DefaultAuth:AuthorizationEndpoint"];
private X509SecurityKey KEY { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.IncludeErrorDetails = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// Ensure token expiry
RequireExpirationTime = true,
ValidateLifetime = true,
// Ensure token audience matches site audience value
ValidateAudience = false,
ValidAudience = AUTH_LOGINPATH,
// Ensure token was issued by a trusted authorization server
ValidateIssuer = true,
ValidIssuer = AUTH_LOGINPATH,
// Specify key used by token
RequireSignedTokens = true,
IssuerSigningKey = KEY
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("Mvc", policy =>
{
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Following Brad's suggestion, 按照布拉德的建议,
Here is a sample of code to perform an OpenId Connect confirguration on ASP NET 2.0 这是在ASP NET 2.0上执行OpenId Connect配置的代码示例
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = Configuration["AuthoritySite"];
options.ClientId = Configuration["ClientId"];
options.ClientSecret = Configuration["ClientSecret"];
options.Scope.Clear();
// options.Scope.Add("Any:Scope");
options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// Compensate server drift
ClockSkew = TimeSpan.FromHours(12),
// Ensure key
IssuerSigningKey = CERTIFICATE,
// Ensure expiry
RequireExpirationTime = true,
ValidateLifetime = true,
// Save token
SaveSigninToken = true
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("Mvc", policy =>
{
policy.AuthenticationSchemes.Add(OpenIdConnectDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
}
More details here: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1 此处有更多详细信息: https : //docs.microsoft.com/zh-cn/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.