...
/Using the Authenticated User When Posting Questions and Answers
Using the Authenticated User When Posting Questions and Answers
Learn how to ensure that only authenticated users can post questions and answers.
We'll cover the following...
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:
We'll start by adding the following using statements in
QuestionsController.cs
:
Press + to interact
using System.Security.Claims;using Microsoft.Extensions.Configuration;using System.Net.Http;using System.Text.Json;
Let's focus on posting a question first by posting it with the authenticated user's ID:
Press + to interact
public async ...PostQuestion(QuestionPostRequestquestionPostRequest){var savedQuestion =await _dataRepository.PostQuestion(newQuestionPostFullRequest{Title = questionPostRequest.Title,Content = questionPostRequest.Content,UserId =User.FindFirst(ClaimTypes.NameIdentifier).Value,UserName = "bob.test@test.com",Created = DateTime.UtcNow}); ...}
...