如何在ASP.NET Web API .NET 6中使基本身份验证可用于我的控制器?

huangapple go评论67阅读模式
英文:

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 &quot;[BasicAuthentication]&quot; to a controller. 

``````````````````````````````````
namespace minimalAPI.Controllers
{
    [Route(&quot;v1/[controller]&quot;)]
    [ApiController]
    [BasicAuthentication]
``````````````````````````````````


I&#39;ve also tried to make the authentication available to the entire application but didn&#39;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>



huangapple
  • 本文由 发表于 2023年3月7日 16:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定