Identity & DotNetCore MVC and others

Heinrich Ludike 21 Reputation points
2021-05-13T07:23:43.303+00:00

I am developing an application with various modules, all of this is hosted on azure.

We have our base application and then all our modules. Our modules are supposed to be logged into, the modules are written in DotNetCore MVC, WebForms, Python pretty much anything.

What would the best practice be to use the credentials that we have on our base application even though the modules do not necessarily have access to the database?
I am currently using API calls, but just like to know if there is a more suitable solution for the problem.

Regards

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,133 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Heinrich Ludike 21 Reputation points
    2021-05-25T09:23:00.603+00:00

    I have implemented JWT bearer tokens and it is working for my APIs. However, with the code implemented I have a slight issue. When I implement the code below it does not seem that my user is authenticating.

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  
                    .AddJwtBearer(options =>  
                    {  
                        options.TokenValidationParameters = new TokenValidationParameters  
                        {  
                            ValidateIssuer = true,  
                            ValidateAudience = true,  
                            ValidateLifetime = true,  
                            ValidateIssuerSigningKey = true,  
                            ValidIssuer = Configuration["Jwt:Issuer"],  
                            ValidAudience = Configuration["Jwt:Issuer"],  
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))  
                        };  
                    });  
                  
    

    99452-image.png
    This is what happens with the code in my startup.cs

    99461-image.png
    This is what happens if I uncomment that section.

    Any idea where the issue might be?


  2. Heinrich Ludike 21 Reputation points
    2021-05-26T07:11:31.163+00:00

    This is still the default code I have in my Areas/Identity/Pages/Account/Manage/Login.cshtml.cs I assume this is where the call for JWT should be made as well?

            public async Task<IActionResult> OnPostAsync(string returnUrl = null)
            {
                returnUrl = returnUrl ?? Url.Content("~/");
    
                if (ModelState.IsValid)
                {
                    // This doesn't count login failures towards account lockout
                    // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User logged in.");
                        return LocalRedirect(returnUrl);
                    }
                    if (result.RequiresTwoFactor)
                    {
                        return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                    }
                    if (result.IsLockedOut)
                    {
                        _logger.LogWarning("User account locked out.");
                        return RedirectToPage("./Lockout");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return Page();
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return Page();
            }
    
    0 comments No comments

  3. Heinrich Ludike 21 Reputation points
    2021-05-26T09:09:16.61+00:00

    This is what I have. I make a call to the AccessController, which executes this code.

    public async Task<JsonResult> UserAuth(string email, string password)
    {
    var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);

    if (result.Succeeded)
    {
        _logger.LogInformation("User logged in.");
    
        var tokenString = GenerateJSONWebToken();
        return new JsonResult(new { token = tokenString });
    }
    

    This is what GenerateJSONWebToken looks like.

    private string GenerateJSONWebToken()
    {
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      _config["Jwt:Issuer"],
      null,
      expires: DateTime.Now.AddMinutes(120),
      signingCredentials: credentials);
    
     return new JwtSecurityTokenHandler().WriteToken(token);
    

    }

    0 comments No comments

  4. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2021-05-26T09:38:16.993+00:00

    Hi @Heinrich Ludike ,

    From the GenerateJSONWebToken method, when you create the JwtSecurityToken instance, the third parameter (Claims) is null, you didn't add claims in JWT token.

    You can refer the following sample code to handle Claims with JWT:

        [HttpPost]    
        [Route("login")]    
        public async Task<IActionResult> Login([FromBody] LoginModel model)    
        {    
            var user = await userManager.FindByNameAsync(model.Username);    
            if (user != null && await userManager.CheckPasswordAsync(user, model.Password))    
            {    
                var userRoles = await userManager.GetRolesAsync(user);    
    
                var authClaims = new List<Claim>    
                {    
                    new Claim(ClaimTypes.Name, user.UserName),    
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),    
                };    
    
                foreach (var userRole in userRoles)    
                {    
                    authClaims.Add(new Claim(ClaimTypes.Role, userRole));    
                }    
    
                var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));    
    
                var token = new JwtSecurityToken(    
                    issuer: _configuration["JWT:ValidIssuer"],    
                    audience: _configuration["JWT:ValidAudience"],    
                    expires: DateTime.Now.AddHours(3),    
                    claims: authClaims,    
                    signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)    
                    );    
    
                return Ok(new    
                {    
                    token = new JwtSecurityTokenHandler().WriteToken(token),    
                    expiration = token.ValidTo    
                });    
            }    
            return Unauthorized();    
        }    
    

    More detail information, check the following articles:

    Authentication And Authorization In ASP.NET 5 With JWT And Swagger

    JWT Authentication In ASP.NET Core


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion