Search⌘ K
AI Features

Using the Authenticated User When Posting Questions and Answers

Explore how to utilize the authenticated user's details when posting questions and answers in a web app. Learn to extract user information from JWT tokens, retrieve additional data from Auth0, and securely associate posts with the correct user ID in ASP.NET Core controllers.

Now that our REST API knows about the user interacting with it, we can use this to post the correct user against questions and answers.

Steps to authenticate users for posting questions and answers

Let's carry out the following steps:

  1. We'll start by adding the following using statements in QuestionsController.cs:

JavaScript (JSX)
using System.Security.Claims;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Text.Json;

  1. Let's focus on posting a question first by posting it with the authenticated user's ID:

JavaScript (JSX)
public async ...
PostQuestion(QuestionPostRequest
questionPostRequest)
{
var savedQuestion =
await _dataRepository.PostQuestion(new
QuestionPostFullRequest
{
Title = questionPostRequest.Title,
Content = questionPostRequest.Content,
UserId =
User.FindFirst(ClaimTypes.NameIdentifier).Value,
UserName = "bob.test@test.com",
Created = DateTime.UtcNow
}); ...
}

...