Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

431
Visualizações
asp.net core custom bearer token and Azure Ad token authorization

i will try my best to explain my question.

currently i am working with a requirement in which user can login with the local db user and can login with the Azure AD, with the local db user i am creating custom token by using below code.

public static string GenerateJwtToken(string userId, string userName, string secret)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(secret);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(ClaimTypes.Name, userName)
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var encryptedToken = tokenHandler.WriteToken(token);

        return encryptedToken;
    }

and validating the token with the below code.

        public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IdentityAppSettings appSettings)
    {
        var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);

        services
            .AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
        return services;
    }

and for Azure AD i am using the below code in the statup.cs class

services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd");

appsettings.json

  "AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "11121313213213132132",
"ClientId": "46853216534163",
"Audience": "api://11121313213213132132"

},

but its throwing below error "Scheme already exists: Bearer"

now my question is how can we use multiple token validator together, and how can we check the token is valid from one so we should not check in another validator.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Thank you Chaodeng. Posting your suggestions as an answer to help other community members.

Need to remove services from AddAuthentication

Azure AD authentication with JWT default scheme JwtBearerDefaults.AuthenticationScheme

Here is the Sample configuration

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer("MyAppName",options =>
            {
                 options.Authority = "Value";
                 options.Audience = "Value";                    
            })
            .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");

Here is the SO for further information

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda