ASP.Net Core Web API中的安全性用户操作 [英] Security user actions in ASP.Net Core Web API

查看:164
本文介绍了ASP.Net Core Web API中的安全性用户操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JWT令牌在ASP.Net Core Web API中创建用于测试身份验证的项目.我实现了使用帐户的基本功能,但是遇到了一些问题.

I create project for test authentication in ASP.Net Core Web API with using JWT tokens. I implemented the basic functionality for working with accounts, but I ran into some problems.

[Authorize]
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly IAuthenticationService _authenticationService;

    public UsersController(
        IUserService userService,
        IAuthenticationService authenticationService)
    {
        _userService = userService;
        _authenticationService = authenticationService;
    }

    // PUT: users/5
    [HttpPut("{id}")]
    public async Task<ActionResult> PutUser(int id, [FromBody]UpdateUserModel model)
    {
        try
        {
            var user = await _userService.UpdateAsync(model, id);

            return Ok();
        }
        catch(Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    // POST : users/authenticate
    [AllowAnonymous]
    [HttpPost("authenticate")]
    public async Task<ActionResult<User>> Authenticate([FromBody] AuthenticateUserModel model)
    {
        var user = await _authenticationService.AuthenticateAsync(model);

        if (user == null)
            return BadRequest(new { message = "Login or password is incorrect" });

        return Ok(user);
    }
}

AuthenticationService:

public async Task<User> AuthenticateAsync(AuthenticateUserModel model)
{
    var users = await _context.Users.ToListAsync();
    var user = users.SingleOrDefault(x => x.Login == model.Login && x.Password == model.Password);

    if (user == null)
        return null;

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            new Claim(ClaimTypes.Name, user.Id.ToString()),
            new Claim(ClaimTypes.Role, user.Role)
        }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    user.Token = tokenHandler.WriteToken(token);

    return user.WithoutPassword();
}

事实证明,授权后,如果我们在要发送请求的客户端中指定其他ID,则任何用户都可以编辑其他用户的数据.是否有可能由于令牌而以某种方式限制了操作,或者这样做会更好吗?

It turns out that after authorization, any user can edit the data of another user if we specify a different id in the client who will send requests. Is it possible to somehow limit the actions thanks to the token or how is it better to do this?

推荐答案

您不应该信任用户提交的数据.您应该像自己所做的那样在有效载荷数据中设置UserId

You should't trust the submitted data from the user. you should set UserId in payload data like what you did yourself

 new Claim(ClaimTypes.Name, user.Id.ToString()),

,当用户编辑数据时,像这样从JWT获取用户ID

and when user edit the data get user id from JWT like this

public int GetCurrentUserId()
{
    var claimsIdentity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;
    var userDataClaim = claimsIdentity?.FindFirst(ClaimTypes.Name);
    var userId = userDataClaim?.Value;
    return string.IsNullOrWhiteSpace(userId) ? 0 : int.Parse(userId);
}

int userId = Convert.ToInt32((User.Identity as ClaimsIdentity).FindFirst(ClaimTypes.Name).Value);

最后

[HttpPut("PutUser")]
public async Task<ActionResult> PutUser([FromBody]UpdateUserModel model)
{
    try
    {
        int userId = Convert.ToInt32((User.Identity as ClaimsIdentity).FindFirst(ClaimTypes.Name).Value);
        var user = await _userService.UpdateAsync(model, userId);
        return Ok();
    }
    catch (Exception ex)
    {
        return BadRequest(new { message = ex.Message });
    }
}

这篇关于ASP.Net Core Web API中的安全性用户操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆