asp.net – Dotnet核心2.0认证多个模式身份cookie和jwt

在dotnet core 1.1 asp中,通过执行以下操作,我能够配置和使用身份中间件,然后使用jwt中间件:
app.UseIdentity();
  app.UseJwtBearerAuthentication(new JwtBearerOptions() {});

现在这已经发生了变化,我们实现了中间件:

app.UseAuthentication();

通过Startup.cs的ConfigureServices部分完成设置的配置。

在迁移文档中有一些使用授权模式的参考:

https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#authentication-middleware-and-services

In 2.0 projects,authentication is configured via services. Each
authentication scheme is registered in the ConfigureServices method of
Startup.cs. The UseIdentity method is replaced with UseAuthentication.

另外还有一个参考:

Setting Default Authentication Schemes

In 1.x,the AutomaticAuthenticate and AutomaticChallenge properties
were intended to be set on a single authentication scheme. There was
no good way to enforce this.

In 2.0,these two properties have been
removed as flags on the individual AuthenticationOptions instance and
have moved into the base AuthenticationOptions class. The properties
can be configured in the AddAuthentication method call within the
ConfigureServices method of Startup.cs:

Alternatively,use an overloaded version of the AddAuthentication
method to set more than one property. In the following overloaded
method example,the default scheme is set to
CookieAuthenticationDefaults.AuthenticationScheme. The authentication
scheme may alternatively be specified within your individual
[Authorize] attributes or authorization policies.

在dotnet core 2.0中是否仍然可以使用多个身份验证模式?我无法让策略尊重JWT配置(“承载”架构),并且只有Identity在配置时才能正常工作。我找不到任何多个身份验证模式的示例。

编辑:

我重读了文档,现在明白了:

app.UseAuthentication()

为默认架构添加自动身份验证。 Identity为您配置默认架构。

通过在Startup.cs配置中执行以下操作,我已经解决了看起来像黑客攻击新api的问题:

app.UseAuthentication();
    app.Use(async (context,next) =>
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            var result = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
            if (result?.Principal != null)
            {
                context.User = result.Principal;
            }
        }

        await next.Invoke();
    });

这是正确的方法,还是我应该利用框架,DI和接口来实现IAuthenticationSchemeProvider的自定义实现?

编辑 – 实施的详细信息以及在何处查找。

可以在此处找到JWT配置,我使用策略来定义授权,其中包括已接受的身份验证架构:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Management/Startup.cs

自定义中间件仍然实现。 Auth控制器在这里:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/AuthController.cs

它使用应用程序生成的API密钥来获取对数据的只读访问权限。您可以在此处找到使用该策略的控制器的实现:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/SitemapController.cs

将数据库连接字符串更改为指向SQL Server,然后运行该应用程序。它会自动迁移数据库并配置管理员用户(support@arragro.com – ArragroPassword1!)。然后转到菜单栏中的“设置”选项卡,然后单击“配置JWT ReadOnly API密钥设置”以获取密钥。在邮递员中,通过配置新选项卡并使用以下地址将其设置为POST来获取jwt令牌:

http://localhost:5000/api/auth/readonly-token

提供标题:Content-Type:application / json

供应身体:

{
    "apiKey": "the api token from the previous step"
}

复制响应中的令牌,然后在邮递员中使用以下内容:

http://localhost:5000/api/sitemap/flat

Authorization: "bearer - The token you received in the previous request"

由于自定义中间件,它将初始工作。注释掉上面提到的代码,然后再试一次,你将获得401。

编辑 – @ DonnyTian的回答在他的评论中涵盖了我的解决方案。我遇到的问题是在UseMvc上设置默认策略,但没有提供架构:

services.AddMvc(config =>
    {
        var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme,IdentityConstants.ApplicationScheme })
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(defaultPolicy));
        config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        config.Filters.Add(new ValidateModelAttribute());
    });

根据建议,这没有自定义中间件。

解决方法

Asp.Net Core 2.0绝对支持多种身份验证方案。
您可以尝试在Authorize属性中指定架构,而不是使用身份验证中间件进行黑客攻击:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我试了一下,它工作得很好。假设您已添加Identity和JWT,如下所示:

services.AddIdentity<ApplicationUser,ApplicationRole>()
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

由于AddIdentity()已将cookie身份验证设置为默认架构,因此我们必须在控制器的Authorize属性中指定架构。目前,我不知道如何覆盖AddIdentity()设置的默认模式,或者我们最好不要这样做。

解决方法是组建一个新类(您可以称之为JwtAuthorize),该类派生自Authorize并将Bearer作为默认模式,因此您不必每次都指定它。

UPDATE

找到了覆盖Identity默认身份验证方案的方法!

而不是下线:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

使用下面的重载来设置默认架构:

services.AddAuthentication(option =>
                {
                    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>....

更新2
如评论中所述,您可以通过将它们连接在一起来启用Identity和JWT身份验证。

[授权(AuthenticationSchemes =“Identity.Application”“,”JwtBearerDefaults.AuthenticationScheme)]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


判断URL文件是不是在于在。private static bool UrlIsExist(string url){ System.Uri u = null; try { u = new Uri(url); } catch { return false; } bool isExist = false;
由于在.net中,Request时出现有HTML或Javascript等字符串时,系统会认为是危险性值。立马报错。解决方案一:在.aspx文件头中加入这句:解决方案二:修改web.config文件:因为validateRequest默认值为true。只要设为false即可。
public static bool ProcessIdCard(this string idCard, out DateTime birthday, out string genderName) { bool result; birthda...
如果你在GridView控件上设置 AllowPaging=&quot;true&quot; or AllowSorting=&quot;true&quot; 而没有使用使用数据源控件 DataSource (i.e. SqlDataSource, ObjectDataSource),运行则会出现下
protected void Page_Load(object sender, EventArgs e){ ScriptManager sm = Page.Master.FindControl(&quot;ScriptManager1&quot;) as ScriptManager; if (sm
1. install all features in IIS2. Try the following steps to register it.run %windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i或运行,跳出如下错误
一般来说一个 HTML 文档有很多标签,比如“”、“”、“”等,想把文档中的 img 标签提取出来并不是一件容易的事。由于 img 标签样式变化多端,使提取的时候用程序寻找并不容易。于是想要寻找它们就必须写一个非常健全的正则表达式,不然有可能会找得不全,或者找出来的不是正确的 img 标签。我们可以
asp.net updatepanel 局部刷新,导致JS不能加载,而无法使用,而且 updatepanel会刷两次,郁闷的。解决方法如下:
FileHandlerhttp://www.cnblogs.com/vipsoft/p/3627709.htmlUpdatePanel无法导出下载文件:http://www.cnblogs.com/vipsoft/p/3298299.html//相对路径下载。path: ~/DownLoad///p
本地能上传文件,部署到服务器上就报Cannot access a closed file 错误,以下是解决方法: 最重要是requestLengthDiskThreshold此属性设置输入流缓冲阈值。
http://tool.oschina.net/commons字符十进制转义字符&quot;&amp;#34;&amp;quot;&amp;&amp;#38;&amp;amp;&amp;#62;&amp;gt;不断开空格(non-breaking space)&amp;#160;HTML特殊转义字符
1、2两步为推荐做法1. 将MySql.Data.dll放到 bin目录下面,或都安装mysql-connector-net-6.0.0.msi2.web.config 添加如下节点,注册版本号一致 3.全局配置在C:\WINDOWS\Microsoft.NET\Framework\v2.0.507
C# 跳转新页面string url = &quot;http://www.vipsoft.com.cn&quot;;ResponseRedirect.Redirect(Response, url, &quot;_blank&quot;, &quot;&#39;toolbar=0,scrollbar
.NET Core 在其上下文中,该请求的地址无效。 看了端口,发现没被占用,后来发现是IP地址变了 改成正确的IP就可以了。
datatable是一个jquery扩展的表格插件。其提供了强大的表格功能。官方地址:http://www.datatables.net/在官方示例中,对于表格的是否可排序是在初始化中设置的一个值来决定的$(&quot;.datatable-simplified&quot;).dataTable(
Html table 细边框 导航页档 军事 历史 ...
C# 跳转新页面判断URL文件是不是在于在。C# 指定物理目录下载文件,Response.End导致“正在中止线程”异常的问题public class FileHandler { public static bool DownLoadFile(string path, string fileName
由于将IE11升级到了 11 之前的网站无法正常使用,如果是开发人员碰到之问题,使用了微软的asp.net 控件,那么将服务器的.net framework 升级到 4.5http://www.microsoft.com/en-us/download/details.aspx?id=30653如果浏
引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个Nginx-Powered AspNet Core Web准生产应用。 在开始之前,我们还是重温一下部署原理,正如你所常见的.Net Core 部署图: 在Linux上部署.Net Core App最好的方式是在Linux机器