Extensão ASP.NET Core para configurar autenticação de token personalizado
dotnet add package Wd3w.AspNetCore.TokenAuthentication
CustomTokenAuthService
Qualquer que seja a sua infraestrutura de autenticação, basta implementar esta interface e registrá-la como serviço.
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
, Essas propriedades são propriedades obrigatórias para trabalhar com o manipulador de autenticação.
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
ao seu controlador ou métodos de ação. [ ApiController ( "[controller]" ) ]
public class SomeController : ControllerBase
{
[ HttpGet ]
[ Authorize ]
public Task < ActionResult > GetSomethingAsync ( )
{
return Task . FromResult ( Ok ( ) ) ;
}
}
Se você precisar fornecer uma mensagem de validação de token de autenticação personalizada, basta lançar AuthenticationFailException
em ITokenAuthService.IsValidateAsync
public class CustomTokenAuthService : ITokenAuthService
{
public async Task < bool > IsValidateAsync ( string token )
{
throw new AuthenticationFailException ( "invalid_format" , "access token couldn't have any special characters." ) ;
}
}
Esta estratégia de versionamento de pacote segue a versão do pacote AspNetCore. Quando houver novos lançamentos sobre o AspNetCore, este pacote também será atualizado.
Apenas a versão secundária é AspNetCore incompatível, que será usada para corrigir bugs e algumas alterações.
Licença MIT
Direitos autorais (c) 2020 WDWWW
É concedida permissão, gratuitamente, a qualquer pessoa que obtenha uma cópia deste software e dos arquivos de documentação associados (o "Software"), para negociar o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, modificar, mesclar , publicar, distribuir, sublicenciar e/ou vender cópias do Software e permitir que as pessoas a quem o Software seja fornecido o façam, sujeito às seguintes condições:
O aviso de direitos autorais acima e este aviso de permissão serão incluídos em todas as cópias ou partes substanciais do Software.
O SOFTWARE É FORNECIDO "COMO ESTÁ", SEM GARANTIA DE QUALQUER TIPO, EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM DETERMINADO FIM E NÃO VIOLAÇÃO. EM HIPÓTESE ALGUMA OS AUTORES OU DETENTORES DE DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUALQUER RECLAMAÇÃO, DANOS OU OUTRA RESPONSABILIDADE, SEJA EM UMA AÇÃO DE CONTRATO, ATO ILÍCITO OU DE OUTRA FORMA, DECORRENTE DE, OU EM CONEXÃO COM O SOFTWARE OU O USO OU OUTRAS NEGOCIAÇÕES NO SOFTWARE.