'How to properly implement authorization code flow in .NET?

I am trying to properly implement Authorization Code flow for a 3rd party REST api for my users to use. However, I am not sure if I am doing it correctly with the redirections. I am storing the Authorization Tokens to Users in the database.

    public async Task<IActionResult> Create(int id, string code)
    {
        var userId = _userManager.GetUserId(User);
        var token = _userService.GetById(userId).AccessToken;
        var tokenExpiration = _userService.GetById(userId).AccessTokenExpiration;

        if (token == null || (DateTime.Now > tokenExpiration))
        {
            if (code != null)
            {
                await _trustapApi.GetToken(userId, "http://localhost:58409/Post/Create/" + id, code);
            } else
            {
                var url = await _trustapApi.GetAuthCode("http://localhost:58409/Post/Create/" + id);
                return Redirect(url);
            }
        }
     }

This is the code I have at the beginning of all API methods. However, I feel like this is redundant. Are there any tutorials or tips on how to properly implement this flow into a .NET project?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source