【问题标题】:Attribute To Secure Web Api保护 Web API 的属性
【发布时间】:2022-01-10 21:52:30
【问题描述】:

我正在使用一个 web api,它应该有一个请求密钥,根据它,api 控制器会做 具体任务。我在 vs 代码中使用了 rest 客户端程序,并做了以下测试:

GET http://localhost:PortNo/WeatherForecast/GetAllTeams
test: "12345678910" //Key

所以在控制器中,我这样做是为了获取键值:

[HttpGet]
public async Task<ActionResult<IEnumerable<TeamDetails>>> GetAllTeams()
{
    string Token = Request.Headers["test"]; //Getting the key value here
    var teams = _service.GetAllTeams();

    return Ok(teams)
}

但我脑子里想的东西很少,做研发,比如我怎样才能用一个属性来做上面的事情。说每个控制器 如果没有找到正确的密钥,将具有如下属性并使请求无效:

[InvalidToken] //This is the attribute
[HttpGet]
public async Task<ActionResult<IEnumerable<TeamDetails>>> GetAllTeams()
{
   var teams = _service.GetAllTeams();

   return Ok(teams)
}

我不确定这是否会使 api 安全,我的计划是验证每个 http 请求(在我的情况下,目前是一个简单的表单提交),所以它应该说请求是从网络生成的api 应用程序。

注意:我之前在小部分中使用过 web api,但现在要实现更广泛的东西,所以希望很少有建议可以帮助我指导更好的设计。

【问题讨论】:

  • 如果您不想在密钥无效时执行,请使用middleware。您可以从那里自行响应。请注意,您可以在任何中间件之前使用它,以便它首先执行。

标签: c# .net-core webapi .net-core-3.1


【解决方案1】:

试试看:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;

..

public class InvalidToken : Attribute, IActionFilter
    {
        
        public InvalidToken( )
        { 
           
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var Authorization = context.HttpContext.Request.Headers["test"];
             
            if ( Authorization != "12345678910")
            {
                context.ModelState.AddModelError("Authorization", "Authorization failed!");
                return;
            }
            
             
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //   "OnActionExecuted" 
            
        }

         
    }

Startup.cs

     services.AddScoped<InvalidToken>();
// add filter to whole api
     services.AddControllers(options =>
                {
                    options.Filters.Add<InvalidToken>();
                });

【讨论】:

  • 我是否需要在 vs code 中为此添加任何包?
  • 不,是纯asp.net核心
  • 我有几件事情搞砸了 - The type or namespace name 'IActionFilter' could not be found (are you missing a using directive or an assembly reference?)The type or namespace name 'ActionExecutingContext' could not be found (are you missing a using directive or an assembly reference?)There is no argument given that corresponds to the required formal parameter 'configuration' of 'InvalidToken.InvalidToken
  • 我添加了需要命名空间
  • 最后一个 - There is no argument given that corresponds to the required formal parameter 'configuration'.
猜你喜欢
  • 2011-03-11
  • 2021-01-05
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 2011-07-31
  • 2015-04-07
  • 1970-01-01
  • 2011-06-06
相关资源
最近更新 更多