删除前如何授权用户?
我正在尝试从用户中删除特定食谱。
[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");
}
邮递员:http://localhost:5000/api/recipes/17我有响应200 OK(正在运行)
但是在这种情况下,随机用户可以从其他用户那里删除配方。
我需要授权来检查用户是否要删除他的食谱。
我添加了授权代码,但这不起作用。每次用户都是未经授权的,因为我无法获取userId。 (这可能是路线问题)
[Authorize]
[Route("api/[controller]")]
[ApiController]
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteRecipe(int userId, int id)
{
if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
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");
}
@ EDIT
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();
});
}
}
}
在ASP .NET Web API中,有一个名为“ ActionFilterAttribute”的类。您可以继承该类。该类具有名为“ OnActionExecuting”的虚拟方法。该方法将在执行action方法之前触发。您可以覆盖该方法并检查用户是否为未授权用户,可以将响应消息作为未授权返回