英文:
How do I make basic authentication available to my controller in asp.net web api .net 6?
问题
我已经实现了一个用户验证类和一个基本身份验证属性类,它通过解码和转换请求头中的令牌来验证。接下来,验证类会检查提供的用户名和密码。即使没有提供用户名或密码,GET请求也会失败以阻止访问数据。
我尝试将 "[BasicAuthentication]" 添加到一个控制器中。
namespace minimalAPI.Controllers
{
[Route("v1/[controller]")]
[ApiController]
[BasicAuthentication]
}
我还尝试使身份验证在整个应用程序中可用,但也没有成功。
namespace minimalAPI
{
public class WebApiConfig
{
public void Register(HttpConfiguration config)
{
config.Filters.Add(new BasicAuthenticationAttribute());
}
}
}
````````````````````````````````````````````````````````````````````
<details>
<summary>英文:</summary>
I have implemented a user validation class and a Basic Authentication Attribute class that verifies the token present in the header of a request by decoding and converting it. Next, the validation class checks the provided username and password. A GET request fails to prevent access to the data even if no username or password is provided.
I tried adding "[BasicAuthentication]" to a controller.
``````````````````````````````````
namespace minimalAPI.Controllers
{
[Route("v1/[controller]")]
[ApiController]
[BasicAuthentication]
``````````````````````````````````
I've also tried to make the authentication available to the entire application but didn't work either.
````````````````````````````````````````````````````````````````````
namespace minimalAPI
{
public class WebApiConfig
{
public void Register(HttpConfiguration config)
{
config.Filters.Add(new BasicAuthenticationAttribute());
}
}
}
````````````````````````````````````````````````````````````````````
</details>
# 答案1
**得分**: 0
尝试将 `[Authorize]` 属性添加到控制器中。以下是在 .NET 6 Web API 中实现基本身份验证的一个良好[示例][1]。
[1]: https://jasonwatmore.com/post/2021/12/20/net-6-basic-authentication-tutorial-with-example-api
<details>
<summary>英文:</summary>
Try adding `[Authorize]` attribute to the controller. Here is good [example][1] to implement basic authentication in .NET 6 Web API
[1]: https://jasonwatmore.com/post/2021/12/20/net-6-basic-authentication-tutorial-with-example-api
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论