2017-10-31 8 views
0

.net 코어 MVC, C#으로 작성된 응용 프로그램이 있습니다. 사용자가 응용 프로그램에 로그인하면 인증 성공 후 다음과 같이 데이터베이스에서 로그인 한 사용자의 클레임이 표시됩니다.사용자 클레임을 토대로 MVC보기 컨트롤 토글

public async Task<IActionResult> Login(LoginInputViewModel model) 
{ 
if (ModelState.IsValid) 
{ 
    //do authentication here 
    //Once user is authenticated then go to next step 

    //Below is the authorization part 

    var userPermission = //getting all the permission from db 

    List<Claim> claims = new List<Claim>(); 
    foreach (var user in userPermission) 
    { 
     claims.Add(new Claim("Permission", user.Permission)); 
     claims.Add(new Claim("FirstName", user.FirstName)); 
     claims.Add(new Claim("LastName", user.LastName)); 
    } 

    // create identity 
    ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie"); 

    // create principal 
    ClaimsPrincipal principal = new ClaimsPrincipal(identity); 
    await HttpContext.SignInAsync(principal); 

} 
else 
{ 
    this.ModelState.AddModelError(string.Empty, "Invalid credentials.");      
    return this.View(inputModel); 
    } 
} 

나는 또한 내 기본 컨트롤러로 한 :

public class BaseController : Controller 
    { 
    public User LoggedInUser 
    { 
     get 
     { 
      return new User(this.User as ClaimsPrincipal); 
     } 
    } 
    } 

나는 모든 코드가 표시되지하고 있지만, 사용자의 위 내 모든 주장은 이름, 성 & 권한

을 즉, 내가 사용하고 반환 이 기본 컨트롤러로 내 집 :

public class HomeController : BaseController 
{ 

} 

설치하고 싶습니다. 내 신청서에 대한 승인. 내 소유권 주장에 이미 권한이 있습니다 (읽기 또는 쓰기 권한 반환). 이러한 권한을 토대로 내보기에 특정 컨트롤을 숨기고 싶습니다. 어떻게해야합니까? 또는 기본 컨트롤러에있는 사용자의 요청이 이미 있으므로 내보기에서 어떻게 액세스 할 수 있습니까? 또는보기에 컨트롤을 권한 부여하는 더 좋은 방법이 있습니다.

의견을 환영합니다. 감사합니다. .

답변

1

1) 당신은 권한 부여 속성을 사용할 수 있습니다 및 claims-based authorization

은 ConfigureServices

services.AddAuthorization(options => 
{ 
    options.AddPolicy("FullAccessOnly", policy => policy.RequireClaim("FullAccess")); 
}); 

에 정책을 추가하고 컨트롤러

public IActionResult SomePage() 
{ 
    return View(); 
} 

[Authorize(Policy = "FullAccessOnly")] 
public IActionResult SomePageWithFullAccess() 
{ 
    return View(); 
} 

2)에서이 정책을 사용하거나 하나를 사용할 수 있습니다 소유권 주장을 확인하고 FullAcess 속성을 사용하여 뷰 모델을 준비하는 방법

3) 또는보기에서 클레임 받기

@{ 
     var fullaccess = User.Claims.Where(x => x.Type == "Permission").FirstOrDefault().Value == "RW" ? true : false; 
    } 

@if(fullaccess){ 
//interface with fullacess 
} else { 
//interface with RO access 
}