Asp.Net Core 3.1.1 MVC在删除[HttpDelete]之前如何授权用户

Asp.Net Core 3.1.1 MVC在删除[HttpDelete]之前如何授权用户,asp.net,asp.net-web-api,asp.net-core-mvc,asp.net-mvc-routing,Asp.net,Asp.net Web Api,Asp.net Core Mvc,Asp.net Mvc Routing,删除前如何授权用户 我正在尝试从用户中删除特定的配方 [HttpDelete("{id}")] public async Task<IActionResult> DeleteRecipe(int userId, int id) { var user = await _repository.GetUser(userId); var recipeFromRepo = await _repository

删除前如何授权用户

我正在尝试从用户中删除特定的配方

  [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRecipe(int userId, int id)
        {

            var user = await _repository.GetUser(userId);

            var recipeFromRepo = await _repository.GetRecipe(id);

            recipeFromRepo.UserId = userId;

            _repository.Delete(recipeFromRepo); 

            if (await _repository.SaveAll())
                return Ok();

            return BadRequest("Failed to delete the recipe");
        }
[HttpDelete(“{id}”)]
公共异步任务DeleteRecipe(int userId,int id)
{
var user=await\u repository.GetUser(userId);
var recipeFromRepo=await_repository.GetRecipe(id);
recipeFromRepo.UserId=UserId;
_删除(recipeFromRepo);
if(wait_repository.SaveAll())
返回Ok();
返回BadRequest(“删除配方失败”);
}
邮递员: 我的回复是200 OK(这正在工作)

但在这种情况下,随机用户可以从其他用户处删除配方

我需要授权来检查用户是否正在删除他的食谱

我添加了授权码,但这不起作用。每次用户都是未经授权的,因为我无法获取用户ID。(很可能这是路线问题)

[授权]
[路由(“api/[控制器]”)]
[ApiController]
[HttpDelete(“{id}”)]
公共异步任务DeleteRecipe(int userId,int id)
{
if(id!=int.Parse(User.FindFirst(ClaimTypes.NameIdentifier.Value))
未经授权返回();
var user=await\u repository.GetUser(userId);
var recipeFromRepo=await_repository.GetRecipe(id);
recipeFromRepo.UserId=UserId;
_删除(recipeFromRepo);
if(wait_repository.SaveAll())
返回Ok();
返回BadRequest(“删除配方失败”);
}
@编辑

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>( x=> x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers().AddNewtonsoftJson(opt => {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddCors();
            services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
            services.AddAutoMapper(typeof(RecipesRepository).Assembly);
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IRecipesRepository, RecipesRepository>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(Configuration
                    .GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder => {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();

                        if(error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(x =>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(x=>x.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”));
services.AddControllers().AddNewtonsoftJson(opt=>{
opt.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.Configure(Configuration.GetSection(“CloudinarySettings”);
AddAutoMapper(typeof(recipes repository).Assembly);
services.addScope();
services.addScope();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>{
options.TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=新的SymmetricSecurityKey(Encoding.ASCII
.GetBytes(配置)
.GetSection(“AppSettings:Token”).Value),
validateisuer=false,
ValidateAudience=false
};
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(生成器=>{
运行(异步上下文=>{
context.Response.StatusCode=(int)HttpStatusCode.InternalServerError;
var error=context.Features.Get();
if(错误!=null)
{
context.Response.AddApplicationError(error.error.Message);
wait context.Response.WriteAsync(error.error.Message);
}
});
});
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
}

在asp.net web api中有一个名为“ActionFilterAttribute”的类。 您可以继承该类。该类具有名为“OnActionExecuting”的虚拟方法。
此方法将在执行操作方法之前激发。如果用户未经授权,您可以覆盖该方法并检查用户。如果您的业务规则包括用户只能删除自己配方的规则,您可以将响应消息返回为未经授权。我建议您在声明中存储userId,并在controller方法中从User.Identity.Name获取它。所以你不需要从外部传递用户ID,因为这真的是个坏主意:)

你在
启动中添加了身份验证和授权中间件了吗?配置了
方法吗?是的,我添加了…你能展示一下你的启动设置,包括中间件和服务注册吗?当然,说注册服务是什么意思?如何注册用户/添加配方?不,只有与身份验证和授权相关的服务,才能使中间件正常工作(即使用用户数据初始化
IHttpContextAccessor
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>( x=> x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers().AddNewtonsoftJson(opt => {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddCors();
            services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
            services.AddAutoMapper(typeof(RecipesRepository).Assembly);
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IRecipesRepository, RecipesRepository>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(Configuration
                    .GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder => {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();

                        if(error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(x =>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}