1

I've a get token method (endpoint) like below. It's decorated with an [AllowAnonymous] annotation - anyone can access this method.

[AllowAnonymous]
[HttpPost("get_token")]
public ActionResult<TokenResponseModel> Authenticate([FromBody] AuthenticateModel authenticateModel, [FromHeader] string jwtToken)
{
    // some code
}

Now once the token is generated, I have step 2 in the authentication process: for that I'm calling the same endpoint with an additional value which is selected from user to generate new token and I'll add the already generated token in header. So I need to create this method as AllowAnonymous also & I need to validate token if I've added token in header like below.

Note: our client doesn't want to create new endpoint for this case.

Please let me know if you have any idea. Thanks

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vasanth R
  • 172
  • 1
  • 1
  • 14
  • If token is empty than use you existing code, otherwise, validate token. See following : https://social.msdn.microsoft.com/Forums/en-US/d89144b0-2e13-4154-acb9-3568ea03ec88/retrieving-access-token-in-controller?forum=aspdotnetcore – jdweng Mar 28 '23 at 12:33
  • @jdweng Sry i'm not able to see validate token code there ? can you post here pls – Vasanth R Mar 28 '23 at 17:19
  • The link is to a Microsoft Webpage. Too much to post. – jdweng Mar 28 '23 at 18:38

1 Answers1

1

So you need the api be able to accept values with or without jwtToken, you can just add a ? in front of the jwtToken parameter to make it Nullable. And call some other internal api(need authorize) with adding the token to header again to when jwtToken is not null.

[AllowAnonymous]
[HttpPost("get_token")]
public ActionResult<TokenResponseModel> Authenticate([FromBody] AuthenticateModel authenticateModel, [FromHeader] string? jwtToken)
{
    if (jwtToken == null) { return token}
    else {
        var request = new HttpRequestMessage(HttpMethod.Get,"https://localhost:7171/otherInternalAPI"); //change to your [Authorize] API
        request.Headers.Add("Authorization", "bearer {your token}");
        var response = await client.SendAsync(request);
        if (response.IsSuccessStatusCode)
        {
            //do something when it can pass jwt authorize.
        }

 }
}
Qiang Fu
  • 1,401
  • 1
  • 2
  • 8
  • yes it will work. but for that I need to create another new endpoint. But our client doesn't want to create new endpoint for this case. – Vasanth R Mar 31 '23 at 08:24
  • @VasanthR Then you have to decode the jwt token and compare the claims as validate. https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token – Qiang Fu Mar 31 '23 at 08:47