그래서 기본적으로 여기에 어떤 사용자는 다른 사용자의 항목을 수정할 수 있습니다. 좋아,이 문장은 이미 사용자에게 응용 프로그램에 사용자 및 항목이 있으며 해당 항목과 관련된 역할이 있음을 알려줍니다. 그리고 그 사용자를 식별 할 수있는 메커니즘이 있습니다. 예를 들어 내장 FormsAuthentication과 같은 일종의 인증을 사용하고 있습니다. 이제는 현재 인증 된 사용자가 다른 사용자에게 속한 제품을 수정하지 않도록하는 방법에 대한 질문이됩니다.
좋아, 사용자에게 속한 항목이 있습니다. 나는이 정보가 서버 어딘가에, 아마 데이터베이스 같은 곳에 저장되어 있다고 생각한다. 한 가지 방법은 요청 된 리소스 id
이 실제로 현재 인증 된 사용자에게 속하는지 확인하는 사용자 지정 인증 특성을 작성하는 것입니다. 당신이 어떤을 사용하지 않는
[MyAuthorize]
public ActionResult AddProduct(int id)
{
// if we get that far we know that the currently authenticated user
// is the owner of the resource pointed by the id parameter and we
// could proceed respectively
...
}
이 방법으로 예를 들면 다음과 같습니다
: 남은 지금
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
// The user is not authenticated or authorized => no need to continue further
return false;
}
// At this stage we know that the user is authorized => we can fetch
// the username
string username = httpContext.User.Identity.Name;
// Now let's fetch the id of the resource he is trying to manipulate from the request
string id = httpContext.Request["id"];
// All that's left is to verify if the current user is the owner
// of the account
return IsOwnerOfItem(username, id);
}
private bool IsOwnerOfItem(string username, string id)
{
// TODO: query the backend to perform the necessary verifications
// about whether the user has permissions to work with the resource
// pointed by the id parameter
throw new NotImplementedException();
}
}
와 모든이 사용자 지정 특성으로 AddProduct
컨트롤러 액션을 장식하는 것입니다 세션 또는 암호화. 암호화는 이미 인증 된 사용자 이름을 안전하게 유지하는 양식 인증 쿠키 형태로 ASP.NET 프레임 워크에 이미 내장되어 있습니다. 이 쿠키는 조작 할 수 없습니다. - 사용자는 다른 사용자로 가장 할 수 없습니다. 따라서 현재 사용자가 누구인지에 대한 보증을 받으면 요청 된 리소스에 액세스 할 수 있는지 여부에 관계없이 필요한 승인을 수행해야합니다.