Api_Action - protected resource with JWT (v2021)

Hi, I wrote this custom API_Action. This is OPEN api, so I can reach it throu POSTMAN without JWT.
Ho can I check JWT token instead (ANM 2021)?

public class GetTableController : ApiController {
    [HttpGet]
    public IActionResult Get([FromBody] Newtonsoft.Json.Linq.JObject data) {
    	string sSQL = "";
    	string columns = INOE(data["Columns"])?"*":sobj(data["Columns"]);
    	string table = INOE(data["Table"])?"":sobj(data["Table"]);
    	string where = INOE(data["Where"])?"TRUE":sobj(data["Where"]);
    	
    	try {
    		sSQL = $"SELECT {columns} FROM `{table}` WHERE {where};";
    	    var rs = ExecuteRows(sSQL);
    	    return Json(rs); // Get the value from route
    	} catch (Exception e) {
            myLogger($"Error: {e}");
            myLogger($"Last SQL: {sSQL}");
            return Ok(new {success=false, message=e.ToString()});
        } 
    }
}

Assuming you have already logged in using the Login API and get the JWT Token, you should be able to login the user using the JWT Token:

        // Get Security object
        Security = ResolveSecurity();

        // Login user
        if (!IsLoggedIn() && !Empty(ClaimValue(ClaimTypes.Name)))
            Security.LoginUser(ClaimValue(ClaimTypes.Name), ClaimValue("Id"), ClaimValue("ParentUserId"), ClaimValue("UserLevelId") ?? "-2");

Let’s say that we obtained the JWT from the LOGIN API.
I have an API_ACTION.
From your code (a part of ValidAPIRequest function) I don’t understand how I can I check the JWT obtained from the LOGIN API.
I tried to do this: this is my code. It is always valid even if I dont pass the “Authorization” header or if I pass a wrong JWT. What is wrong?

public class GetTableController : ApiController {
    [HttpPost]
    public IActionResult Post(object jsonData) {

        var security = ResolveSecurity();
        if (IsApi()) { // API
        	myLogger("THIS IS API CALL");
        	if (ValidApiRequest()) {
        		myLogger("THIS IS A VALID API REQUEST");
        		//So here I can run my AUTHENTICATED code block
            } else {
            	myLogger("THIS IS A NOT VALID API REQUEST");
            	return Ok(new {success=false, message="NO VALID REQUEST"});
            }

         } else {
            	myLogger("NO IS API");
            	return Ok(new {success=false, message="NO VALID REQUEST"});
         }
    }
}

You need to add your own checking. For example:

if (security.IsLoggedIn) { // Check if logged in
//... processing here
}

ok. does the security.IsLoggedIn check the JWT sent thru the authorization header request or do I have to check its validity by myself?

The security.IsLogged is from Advanced Security of ASP.NET Maker, not related to JWT. To check JWT also,In v2021, you can try using attribute for your controller:

[Authorize(Policy = "JwtUserLevel")]

In v2022, you should use:

[Authorize(Policy = "ApiUserLevel")]

This is my code modified as suggested (ANM 2021)
It gives to me the following error. I haven’t found in ANM source any reference to JwtUserLevel… maybe ApiUserLevel?System.InvalidOperationException: The AuthorizationPolicy named: ‘JwtUserLevel’ was not found.

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Authorization: Bearer: 123
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 66
Content-Type: application/json
Host: kidsappmobileapi.local
User-Agent: PostmanRuntime/7.29.2
Postman-Token: 879b5987-2f4c-48c8-9ff6-2e90f66516d7



[Authorize(Policy = "JwtUserLevel")]
public class GetTableController : ApiController {
    [HttpPost]
    public IActionResult Post(object jsonData) {

        var security = ResolveSecurity();
        if (IsApi()) { // API
        	myLogger("DENTROAPI");
        	if (ValidApiRequest()) {

        		myLogger("SI VALIDAPIREQUEST");
        		if ((security.IsLoggedIn)) {
        			myLogger("SI ISLOGGEDIN");        		
        			//here I have my code block to run for JWT AUTHENTICATED users
    			} else {
            		myLogger("NO ISLOGGEDIN");
            		return Ok(new {success=false, message="NO LOGGED IN"});
    			
    			}
            } else {
            	myLogger("NO VALIDAPIREQUEST");
            	return Ok(new {success=false, message="NO VALID REQUEST"});
            }

         } else {
            	myLogger("NO IS API");
            	return Ok(new {success=false, message="NO VALID REQUEST"});
         }
    }
}

It should be: (both v2021 and v2022)[Authorize(Policy = “ApiUserLevel”)]You better open your project in Visual Studio 2022 to test and debug your codes directly.