問題描述
在 dotnet core 1.1 asp 中,我能夠通過執行以下操作來配置和使用身份中間件和 jwt 中間件:
In dotnet core 1.1 asp, I was able to configure and use identity middleware followed by jwt middleware by doing the following:
app.UseIdentity();
app.UseJwtBearerAuthentication(new JwtBearerOptions() {});
這已經改變了,我們使用以下實現中間件:
This has now changed in that we implement the middleware with:
app.UseAuthentication();
設置的配置是通過 Startup.cs 的 ConfigureServices 部分完成的.
Configuration of the settings is done via the ConfigureServices section of Startup.cs.
遷移文檔中有一些關于使用授權模式的參考:
There are some references to the use of authorization schema's in the migration documentation:
https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#authentication-middleware-and-services
在 2.0 項目中,身份驗證是通過服務配置的.每個身份驗證方案在 ConfigureServices 方法中注冊啟動.cs.UseIdentity 方法被替換為 UseAuthentication.
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.
另外還有一個參考:
在 1.x 中,AutomaticAuthenticate 和 AutomaticChallenge 屬性旨在設置在單個身份驗證方案上.有沒有很好的方法來執行這一點.
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.
在 2.0 中,這兩個屬性已經作為單個 AuthenticationOptions 實例上的標志刪除,并且已移至基本 AuthenticationOptions 類.屬性可以在 AddAuthentication 方法調用中配置Startup.cs 的 ConfigureServices 方法:
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:
或者,使用 AddAuthentication 的重載版本方法來設置多個屬性.在下面重載方法示例,默認方案設置為CookieAuthenticationDefaults.AuthenticationScheme.認證方案也可以在您的個人中指定[授權] 屬性或授權策略.
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 配置(Bearer"模式)的策略,并且目前只有 Identity 與這兩個配置一起工作.我找不到多個身份驗證模式的任何示例.
Is it still possible in dotnet core 2.0 to use multiple authentication schemas? I cannot get the policy to respect the JWT configuration ("Bearer" schema), and only Identity is working at present with both configured. I can't find any samples of multiple authentication schemas.
我重新閱讀了文檔,現在明白了:
I've reread the documentation, and now understand that the:
app.UseAuthentication()
添加針對默認架構的自動身份驗證.Identity 為您配置默認架構.
adds automatic authentication against a default schema. Identity configures the default schemas for you.
通過在 Startup.cs 配置中執行以下操作,我已經解決了似乎針對新 api 的黑客攻擊的問題:
I have gotten around the issue with what seems like a hack working against the new api's by doing the following in Startup.cs Configure:
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 的實現?
Is this the correct way to do this, or should I be utilising the framework, DI and interfaces for custom implementations of IAuthenticationSchemeProvider?
編輯 - 實現的更多細節以及在哪里可以找到它.
Edit - Futher details of the implementation and where to find it.
JWT 配置可以在這里找到,我正在使用策略來定義授權,其中包括接受的身份驗證模式:
The JWT Config can be found here, and I am using policies to define the authorization, which include the accepted auth schema's:
https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Management/Startup.cs
自定義中間件仍在實施.Auth 控制器在這里:
Custom middleware is still implemented. The Auth controller is here:
https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/AuthController.cs
它使用應用程序生成的 API 密鑰來獲得對數據的只讀訪問權限.您可以在此處找到使用該策略的控制器的實現:
It uses API Keys generated by the app to get read only access to data. You can find the implementation of a controller utilising the policy here:
https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/SitemapController.cs
更改數據庫連接字符串以指向您的 SQL Server,然后運行應用程序.它會自動遷移數據庫并配置管理員用戶 (support@arragro.com - ArragroPassword1!).然后轉到菜單欄中的設置"選項卡并單擊配置 JWT ReadOnly API 密鑰設置"以獲取密鑰.在 postman 中,通過配置新選項卡并將其設置為 POST 并使用以下地址獲取 jwt 令牌:
Change the DB Connection string to point to your SQL Server, and run the application. It migrates the DB automatically and configures an admin user (support@arragro.com - ArragroPassword1!). Then go to the Settings tab in the menu bar and click "Configure the JWT ReadOnly API Key Settings" to get a key. In postman, get a jwt token by configuring a new tab and setting it to POST with the following address:
http://localhost:5000/api/auth/readonly-token
提供標頭:Content-Type: application/json
Supply the headers: Content-Type: application/json
供應身體:
{
"apiKey": "the api token from the previous step"
}
復制響應中的令牌,然后在郵遞員中使用以下內容:
Copy the token in the response, and then use the following in postman:
http://localhost:5000/api/sitemap/flat
Authorization: "bearer - The token you received in the previous request"
由于自定義中間件,它最初可以工作.把上面提到的代碼注釋掉,再試一次,就會收到401.
It will work inititally because of the custom middleware. Comment out the code mentioned above and try again and you will receive a 401.
編輯 -@DonnyTian 下面的回答涵蓋了我在他的評論中的解決方案.我遇到的問題是在 UseMvc 上設置默認策略,但不提供架構:
Edit -@DonnyTian's answer below covers my solution in his comments. The problem I was having was setting a default policy on UseMvc, but not supplying the schema's:
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());
});
按照建議,這無需自定義中間件即可工作.
Following the advice, this works without custom middleware.
推薦答案
Asp.Net Core 2.0 絕對支持多種認證方案.您可以嘗試在 Authorize
屬性中指定架構,而不是使用身份驗證中間件進行黑客攻擊:
Asp.Net Core 2.0 definitely support multiple authentication schemes.
Rather than a hacking with authenticate middleware, you can try to specify the schema in Authorize
attribute:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
我試了一下,效果很好.假設您已添加 Identity 和 JWT,如下所示:
I gave a try and it worked fine. Assuming you have added both Identity and JWT as below:
services.AddIdentity<ApplicationUser, ApplicationRole>()
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
由于 AddIdentity()
已經將 cookie 身份驗證設置為默認模式,我們必須在控制器的 Authorize
屬性中指定模式.目前,我不知道如何覆蓋 AddIdentity()
設置的默認模式,或者我們最好不要這樣做.
Since AddIdentity()
already set cookie authentication as the default schema, we have to specify schema in Authorize
attribute of controllers. For now, I have no idea how to overwrite the default schema set by AddIdentity()
, or maybe we'd better not to do that.
一種解決方法是編寫一個派生自 Authorize
并將 Bearer 作為默認架構的新類(您可以將其稱為 JwtAuthorize),因此您不需要每次都要指定.
A work around is to compose a new class (you can call it JwtAuthorize) that derives from Authorize
and have Bearer as the default schema, so you don't have to specify it every time.
更新
找到了覆蓋 Identity 默認身份驗證方案的方法!
Found the way to override Identity default authentication scheme!
而不是下面的行:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
使用下面的重載來設置默認架構:
Use below overload to set default schema:
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>....
更新 2如評論中所述,您可以通過將 Identity 和 JWT auth 連接在一起來啟用它們.<代碼>[授權(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]
UPDATE 2
As mentioned in comments, you can enable both Identity and JWT auth by join them together.
[Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]
這篇關于Dotnet core 2.0 身份驗證多模式身份 cookie 和 jwt的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!