.Net core UI proj [Authorize] and API trying to access this controller action

Andrew Harkins 46 Reputation points
2021-06-17T21:02:19.513+00:00

Hello all,
I been working hard on my project and its almost ready to be released into production. Now 1 thing has just come up that im not positive about how to handle. I have a Front end MVC Core UI project and a back end .Net Core Web API. My WebAPI is making an httpclient call to my UI controller that has an [authorize] attirubte on it. (I know its usually the opposite way but for this circumstance it must to this) How would I authorize my API to call this controller action?
I have cookie auth and JWT auth. My default is cookie auth.

// API
string trade = JsonSerializer.Serialize(tradeVM);//"TraderUI"
                using var client = _httpClient.CreateClient();
                client.BaseAddress = new Uri("https://localhost:50111");
                //using var response = await client.PostAsync($"/HarkinsTrader/GetTradeStatusUpdate/",
                using var response = await client.PostAsync($"/HarkinsTrader/SendTradeStatusUpdate/",
                        new StringContent(trade, Encoding.UTF8, "application/json"));
                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Success StreamStatus Update");
                    return Ok();
                }
[HttpPost]
public async Task<IActionResult> SendTradeStatusUpdate([FromBody] TradeResultVM model)
        {
            _logger.LogInformation("Inside GetTradeStatus");
     
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Andrew Harkins 46 Reputation points
    2021-06-21T13:26:51.497+00:00

    Thank you, Sorry about the late reply.
    This is not the answer, its just my current code. it wouldnt let me post it in a reply.
    Yes my application first uses cookie auth to login. I then have it calling an API which I would like to use JWT auth which opens a websocket stream (Im debating and putting this stream on the UI) when the API gets an update it calls the UI and I want this one call to be a JWT Auth, I tried a bunch of things this past weekend but i keep getting invalid signature or SSL cert is invalid.

    Both projects are .Net Core. One is a web api and the other is a MVC project
    Its actually 2 APIS and MVC (userAPI, TraderAPI and the UI)

    `User API
    
            public string GenerateJWTToken(UserRoleVM user)
            {
                if (user != null)
                {
                    var secretKey = Base64UrlEncoder.DecodeBytes(_config.GetSection("Tokens:Key").ToString());
                    var securityKey = new SymmetricSecurityKey(secretKey);
                    var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
                    var currentTime = DateTime.Now;
                    var claims = new Claim[]
                    {
                         new Claim(JwtRegisteredClaimNames.Sub, user.UserName)
                        ,new Claim(JwtRegisteredClaimNames.Sid, user.UserGUID)
                        ,new Claim(JwtRegisteredClaimNames.NameId, user.UserID.ToString())
                        ,new Claim(JwtRegisteredClaimNames.Email, user.Email)
                        ,new Claim(JwtRegisteredClaimNames.AuthTime, currentTime.ToString())
                        ,new Claim(ClaimTypes.Role, user.Role)
                        //,new Claim(JwtRegisteredClaimNames.)
                        ,new Claim(type: "Subscribed", value: user.IsSubscribed.ToString())
                        ,new Claim(type: "SubscribedDate", value: user.DateSubscribed.ToString())
    
                    };
    
                    var jwtSecurityToken = new JwtSecurityToken
                        (
                            signingCredentials: signingCredentials,
                            audience: _config.GetValue<string>("Tokens:Audience"),
                            issuer: _config.GetValue<string>("Tokens:Issuer"),
                            expires: currentTime.AddMinutes(_config.GetValue<int>("Tokens:LifeTime")),
                            //notBefore: currentTime,
                            claims: claims
                        );
                    return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                }
                return null;
            }
    
            //public Task<LoginResponseVM> Login(string username, string password)
            public async Task<string> Login(string username, string password)
            {
                string jwtToken = null;
                if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
                {
                    try
                    {
                        var result = await _signInManager.PasswordSignInAsync(username, password, false, false);
                        if (result.Succeeded)
                        {
                            //var savedUser = await _userService.GetUserByNameAsync(username);
                            //var role = await _userService.GetUserRolesAsync(savedUser);
                            var userVM = await _userService.GetUserNRole2Async(username);
                            //jwtToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(GenerateJWTToken(userVM)));
                            jwtToken = GenerateJWTToken(userVM);
    
                        }
                    }
                    catch (Exception ex)
                    {
    
                    }
                }
                return jwtToken;
            }
    
    TraderAPI
     [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]        
            [HttpPost]
            //public async Task<IActionResult> GetTradeStatusUpdate([FromBody] TradeResultVM model)
            public async Task<IActionResult> SendTradeStatusUpdate([FromBody] TradeResultVM model)
            {
                _logger.LogInformation("Inside GetTradeStatus");
    
                var lstTradeStatuses = await GetLstTradeStatuses();
                if (lstTradeStatuses != null)
                {
                    await _semaphoreSlimS.WaitAsync();
                    try
                    {
                        foreach (var activeTrade in lstTradeStatuses)
                        {
                            if (activeTrade.TradeID == model.TradeID)
                            {
                                _logger.LogInformation("Trade found in lstTradeStatuses");
              ...
    }
    
            [HttpPost("SendUITradeStatusV4")]
            public async Task<IActionResult> SendUITradeStatusV4(BinanceStreamOrderUpdate orderUpdate, string token)
            {
                if (orderUpdate != null)
                {
                    TradeResultVM tradeVM = new TradeResultVM
                    {
                        //TradeName = "Test",
                        TradeID = orderUpdate.OrderId,
                        TradeSymbol = orderUpdate.Symbol,
                        Price = orderUpdate.Price,
                        Quantity = orderUpdate.Quantity                  
                    };
    
                    string trade = JsonSerializer.Serialize(tradeVM);//
                    using var client = _httpClient.CreateClient("TraderUI");
    
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                    //client.BaseAddress = new Uri("https://localhost:50111");
                    //using var response = await client.PostAsync($"/HarkinsTrader/GetTradeStatusUpdate/",
                    _logger.LogInformation("Sending Key");
                    using var response = await client.PostAsync($"/HarkinsTrader/SendTradeStatusUpdate/",
                            new StringContent(trade, Encoding.UTF8, "application/json"));
                    if (response.IsSuccessStatusCode)
                    {
                        _logger.LogInformation("Success StreamStatus Update");
                        return Ok();
                    }
                }
                return BadRequest();
            }
    
    `