Await without async Task

It's now 3 days and I still cannot find a single clear answer as to what exactly I am supposed to do with the jwt token I get back from the API. I've browsed possibly 100 different articles and the code is either incomplete or the writers themselves are just copy pasting from other obscure articles.

I don't have identity framework. This is a bare bones MVC front end. I get told hundreds of times to populate the middleware with this and put my key in the appsettings and the walla it magically authenticates yes none of them can prove how and their projects are incomplete. They all very excitedly explain how retrieve the token from the API and validate it....................and then stop dead short right there. Not 1 single article has explained from there on what to do.

All I want to do is use the key I get back to add authorization headers on my controllers. Thats it. My faith in sites like stackoverflow, codeproject, csharp tutorials and even Microsoft's own documentation has fallen at an all time low tbh. Its a simple thing I am trying to achieve and yet nobody has a simple explanation. What do I do guys?
 
Last edited:
The token you get back goes into a header named “Authentication”, with the value “Bearer [token]”

“services.AddAuthentication”, “app.UseAuthentication”, “app.UseAuthorisation” in Startup.cs handles the authentication part.

the best way to test this is with postman/insomnia.

make a very basic endpoint with the “Authorized” attribute.
call it in postman, it will 401.
call the login endpoint with credentials, and it will return the token.
modify your previous 401 request to include authentication header.
call again and you will get 200
 
The token you get back goes into a header named “Authentication”, with the value “Bearer [token]”

“services.AddAuthentication”, “app.UseAuthentication”, “app.UseAuthorisation” in Startup.cs handles the authentication part.

the best way to test this is with postman/insomnia.

make a very basic endpoint with the “Authorized” attribute.
call it in postman, it will 401.
call the login endpoint with credentials, and it will return the token.
modify your previous 401 request to include authentication header.
call again and you will get 200

How does it go into the header? Must I put it in there somehow?

I get the token value back into a variable and there is basically sits :thumbsup:
 
sorry, the header name is "Authorization", but was typing on my phone

depends on the HTTP client you are using.

axios:
Code:
axios.get('/my/endpoint', {headers: { Authorization: "Bearer [token]" }});

.Net HttpClient
Code:
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {credentials}");


This is why I say, get this working via postman first
 
I think the penny dropped with what you said specifically about the status 200 OK. Mine is not returning this in then header in fact its returning the date and time haha.

I think you have come to the rescue again. I'll let you know. Just going back to the API to sort that out and then will try your above suggestion. Its kind of making sense now.
 
I don't have identity framework. This is a bare bones MVC front end. I get told hundreds of times to populate the middleware with this and put my key in the appsettings and the walla it magically authenticates yes none of them can prove how and their projects are incomplete. They all very excitedly explain how retrieve the token from the API and validate it....................and then stop dead short right there. Not 1 single article has explained from there on what to do.
That's kinda the issue, you should already know what you want to do with it since it's not limited to one platform.
You won't find docs for using JWTs in MVC because you control the UI server side, you can check the user's data in Razor unlike a SPA.
Cookies are simpler for backend developers without needing Identity.

There's a lot of overhead to using JWTs that you're skipping over which will hurt you later.
Stateless => JWTs are valid until they expire or the validation fails(encryption key change), if a user changes their password or claims/role then you need to create a new JWT, also keep a blacklist of revoked JWTs.
Facebook got this wrong, https://www.cnbc.com/2018/09/28/fac...n-accounts-investigation-in-early-stages.html
Browser security => Once you start making API requests in the browser with JS, then you need to start worrying about keeping that JWT safe from XSS, configuring CORS etc.
Microsoft got this wrong, https://github.com/oskarsve/ms-teams-rce
 
Still on the same project. Arguing with end points now. Please can any of you point out why the Id is not being passed to the API controller. I'm doing something wrong and it's been plaguing me for a while now. It's nothing fancy I have just stripped away much of the code and left the basics.

I am literally stumped.

C#:
[HttpPut]
public async Task<IActionResult> PutEmployee(int id, [FromBody] EmployeeDto emp)
{
    if (id != emp.Id)
    {
        return BadRequest(ModelState);
    }
  
    var result = await _userService.UpdateEmployee(emp);

    if (result)
    {
        return Ok(emp);
    }

    return NotFound();
}

C#:
static void Main(string[] args)
{
    EmployeeDto emp = new EmployeeDto
    {
        Id = 1,
        FirstName = "TestFirstName",
        LastName = "TestLastName",
        EmailAddress = "[email protected]",
        ProfilePicture = "403c44bd-5fd6-4508-9f4c-9d5dd08be5d3_defaultProfileImage.jpg",
        RoleId = 1
    };

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://localhost:44128");
        var response = client.PutAsJsonAsync("/api/employees", emp).Result;
    }
}
 
You would need to call /api/employees/1

that is assuming that mvc is doing auto binding. Might have to do /api/employees?id=1

sorry. Not familiar with mvc
 
You would need to call /api/employees/1

that is assuming that mvc is doing auto binding. Might have to do /api/employees?id=1

sorry. Not familiar with mvc
Thanks I'll try that. I wasn't coming right in MVC so quickly smashed a console app to test the request and was still failing. Will give that a go.
 
Ok I see. That is actually a web api controller?

personally I don’t use the convention based urls and prefer to define the route and the parameters in the HttpGet/Post/Put/Delete attribute.
E.g.
On the controller class:
[Route(“/api/employees”)]

On the controller method:
[HttpGet(“{id}”)] // handles e.g. /api/employees/1
public ActionResult Get(int id)

Sorry about the non-formatted code, typing this on my phone
 
I get it yeah ok decorate them so basically enforce a standard. Let me try that.
 
Top
Sign up to the MyBroadband newsletter
X