基于策略和资源的授权机制
This commit is contained in:
1 parent
2d0e504108
commit
65925ce6ef
13 files changed
+172
-51
No files matched your search
@@ -1,5 +1,7 @@
|
||||
using HelloShop.IdentityService.Entities;
|
||||
using HelloShop.IdentityService.EntityFrameworks;
|
||||
using HelloShop.ServiceDefaults.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
|
||||
@@ -11,24 +13,66 @@ namespace HelloShop.IdentityService.Controllers
|
||||
public class UsersController(IdentityServiceDbContext dbContext) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public IEnumerable<User> Get()
|
||||
[Authorize(IdentityPermissions.Users.Default)]
|
||||
public IEnumerable<User> GetUsers()
|
||||
{
|
||||
return dbContext.Set<User>();
|
||||
}
|
||||
|
||||
// GET api/<UsersController>/5
|
||||
[HttpGet("{id}")]
|
||||
public User? Get(int id)
|
||||
[Authorize(IdentityPermissions.Users.Default)]
|
||||
public User? GetUser(int id)
|
||||
{
|
||||
return dbContext.Set<User>().Find(id);
|
||||
}
|
||||
|
||||
// POST api/<UsersController>
|
||||
[HttpPost]
|
||||
public void Post([FromBody] User value)
|
||||
[Authorize(IdentityPermissions.Users.Create)]
|
||||
public void PostUser([FromBody] User value)
|
||||
{
|
||||
dbContext.Add(value);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
[Authorize(IdentityPermissions.Users.Update)]
|
||||
public void PutUser(int id, [FromBody] User value)
|
||||
{
|
||||
var user = dbContext.Set<User>().Find(id);
|
||||
if (user != null)
|
||||
{
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize(IdentityPermissions.Users.Delete)]
|
||||
public async Task<IActionResult> DeleteUser(int id, [FromServices] IAuthorizationService authorizationService)
|
||||
{
|
||||
var user = dbContext.Set<User>().Find(id);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
var result = await authorizationService.AuthorizeAsync(User, user, IdentityPermissions.Users.Delete);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
dbContext.Remove(user);
|
||||
|
||||
dbContext.SaveChanges();
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
[HttpGet(nameof(Bar))]
|
||||
[Authorize(IdentityPermissions.Users.Create)]
|
||||
public IActionResult Bar()
|
||||
{
|
||||
return Ok("Hello, World!");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user