0
votes

In my web project i want to enable the user to login with username / password and Microsoft Account. Tech - Stack:

  • Asp.Net Core WebApi
  • Angular
  • Azure App Service

First i created the username / password login. Like this:

StartUp.cs:

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JWTKey"].ToString())),
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true

            };
        });

Login Method:

    public async Task<IActionResult> ClassicAuth(AuthRequest authRequest)
    {
        tbl_Person person = await _standardRepository.Login(authRequest.Username, authRequest.Password);

        if (person != null)
        {

            var claims = new[]
            {
                    new Claim(ClaimTypes.GivenName, person.PER_T_Firstname),
            };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config["JWTKey"].ToString()));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddHours(24),
                SigningCredentials = creds
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return Ok(tokenHandler.WriteToken(token));
        }
        else
            return Unauthorized("Invalid login data");
    }

And secured my api enpoints with [Authorize].So far so good...that works.

Now i want to add a login method with Microsoft Account. I use Azure App Service Authentication / Authorization for that (https://docs.microsoft.com/de-de/azure/app-service/overview-authentication-authorization).

I configured the auth provider and i'm able to start the auth flow with a custom link in my angular app:

enter image description here

<a href="https://mysite.azurewebsites.net/.auth/login/microsoftaccount">Login with Microsoft - Account</a>

This works and i can retrieve the access token from my angular app with this:

this.httpClient.get("https://mysite.azurewebsites.net/.auth/me").subscribe(res => {
  console.log(res[0].access_token);
});

Now the problem:

access_token seems not a valid JWT Token. If i copy the token and go to https://jwt.io/ it is invalid.

When i pass the token to my API i get a 401 - Response. With seems logical because my API checks if the JWT Token is signed with my custom JWT Key and not the Key from Microsoft.

How can I make both login methods work together? I may have some basic understanding problems at the moment.

1
Sorry @OPunktSchmidt, for the invalid solution before. After checking your issue again, I update a sample maybe helpful for you.Doris Lv

1 Answers

2
votes

It seems you want your Angular app calling an ASP.NET Core Web API secured with Azure Active Directory, here is a sample works well for that.

The most important step is register the app in AAD.enter image description here

By the way, if you want to enable users to login one project with multiple ways in azure, you can use multiple sign-in providers.