用於配置自訂令牌驗證的 ASP.NET Core 擴充
dotnet add package Wd3w.AspNetCore.TokenAuthentication
CustomTokenAuthService
無論您的身分驗證基礎架構是什麼,只需實現此介面並將其註冊為服務即可。
public class CustomTokenAuthService : ITokenAuthService
{
private CustomDb _db { get ; set ; }
public CustomTokenAuthService ( CustomDb db )
{
_db = db ;
}
public async Task < bool > IsValidateAsync ( string token )
{
return await _db . AccessTokens . AnyAsync ( accessToken => accessToken . Key == token ) ;
}
public async Task < ClaimsPrincipal > GetPrincipalAsync ( string token )
{
// Do create your own custom claims pricipal object and return them;
return new .. .
}
}
AddTokenAuthenticationScheme<TService>
將自訂令牌方案新增至身份驗證建構器Realm
、 TokenLength
,這些屬性是工作身分驗證處理程序所需的屬性。
services . AddAuthentication ( "Bearer" )
. AddTokenAuthenticationScheme < CustomTokenAuthService > ( "Bearer" , new TokenAuthenticationConfiguration
{
Realm = "www.example.com/sign-in" ,
TokenLength = 21 ,
// AuthenticationType = "Bearer" - this value is optional, default is from scheme parameter value.
} ) ;
AuthorizeAttribute
附加到您的控制器或操作方法。 [ ApiController ( "[controller]" ) ]
public class SomeController : ControllerBase
{
[ HttpGet ]
[ Authorize ]
public Task < ActionResult > GetSomethingAsync ( )
{
return Task . FromResult ( Ok ( ) ) ;
}
}
如果您需要提供自訂身份驗證令牌驗證訊息,只需在ITokenAuthService.IsValidateAsync
上拋出AuthenticationFailException
public class CustomTokenAuthService : ITokenAuthService
{
public async Task < bool > IsValidateAsync ( string token )
{
throw new AuthenticationFailException ( "invalid_format" , "access token couldn't have any special characters." ) ;
}
}
此套件版本控制策略遵循 AspNetCore 套件版本。當有關於 AspNetCore 的新版本時,此套件也會更新。
只有次要版本與 AspNetCore 不匹配,它將用於修復錯誤和一些更改。
麻省理工學院許可證
版權所有 (c) 2020 WDWWW
特此免費授予任何獲得本軟體和相關文件文件(「軟體」)副本的人不受限制地使用本軟體,包括但不限於使用、複製、修改、合併的權利、發布、分發、再授權和/或銷售軟體的副本,並允許向其提供軟體的人員這樣做,但須滿足以下條件:
上述版權聲明和本授權聲明應包含在本軟體的所有副本或主要部分中。
本軟體以「現況」提供,不提供任何明示或暗示的保證,包括但不限於適銷性、特定用途的適用性和不侵權的保證。 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE軟體.