1

그래서 WebApi 메서드를 호출하는 MVC 응용 프로그램이 있습니다.Web.Api의 기본 토큰 인증 및 권한 부여

MVC 응용 프로그램에 내 인증이

public class CustomAuthorizeAttribute : AuthorizeAttribute { 

     private RolesEnum _role; 

     public CustomAuthorizeAttribute() { 
      _role = RolesEnum.User; 
     } 

     public CustomAuthorizeAttribute(RolesEnum role) { 
      _role = role; 
     } 

     protected override bool AuthorizeCore(HttpContextBase httpContext) { 

      User currentUser = (User)httpContext.Session["CurrentUser"]; 

      if (currentUser == null) { 
       return false; 
      } 

      if (currentUser.Role == RolesEnum.User && _role == RolesEnum.Admin) { 
       return false; 
      } 

      return true; 
     } 

위한 인증과 같이 이루어집니다

[HttpPost] 
    public ActionResult Login(string username, string password) 
    { 

     User acc = new User(); 
     acc.Username = username; 
     acc.Password = password; 
     acc = accBL.Login(acc); 

     if (acc != null) { 
      Session.Add("CurrentUser", acc); 
      return RedirectToAction("Index", "Project", null); 
     } else { 
      return View(); 
     } 


    } 

로그인 방법이

public User LogIn(User acc) { 
      try { 
       HttpClient client = new HttpClient(); 
       client.BaseAddress = new Uri(BASE_URL); 
       client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json")); 
       HttpResponseMessage response = client.PostAsJsonAsync("api/Account/Login", acc).Result; 

       if (response.IsSuccessStatusCode) { 
        return response.Content.ReadAsAsync<User>().Result; 
       } else { 
        return null; 
       } 

      } catch { 
       return null; 
      } 
     } 

그리고 WebApi 방법처럼 보이는 WebApi 메소드를 호출 완료 이 모양은

입니다.
[Route("api/Account/Login")] 
     [HttpPost] 
     public IHttpActionResult Login(User userModel) { 
      User user = db.Users.Where(p => p.Username == userModel.Username && p.Password == userModel.Password).FirstOrDefault(); 

      if (user != null) { 
       return Ok(user); 
      } else { 
       throw new HttpResponseException(HttpStatusCode.Unauthorized); 
      } 

     } 

어떻게하면 MVC App과 WebApi 서비스를 연결할 수 있습니까? 내 권한 부여 및 인증은 MVC 부분에서 작동하지만 WebApi 서비스를이 권한/인증없이 호출 할 수 있습니다. 예제를 기반으로 WebApi도 보호 할 수 있습니까? 나는 MVC와 WebApi로 약 3 주간 일해 왔으며 많은 것들이 나에게 너무 분명하지 않다.

공개 IHttpActionResult 로그인 (사용자 userModel)에 GUID를 만들고 메서드가 호출 될 때마다 확인해야합니까? 이 GUID를 MVC App 및 MVC에서 WebApi로 전달하는 방법은 무엇입니까?

답변

1

WebAPI Login() 메서드에서 일종의 토큰 (예 : JWT)을 만들고 MVC 응용 프로그램에 Ok() 응답과 함께 반환 할 수 있습니다. API 끝점을 호출하는 사용자는이 토큰을 다시 보내야합니다 (예 : 맞춤 '토큰'헤더에 있음). API 끝점에서 사용하는 사용자 지정 WebAPI 권한 부여 특성 내에서 토큰의 유효성을 검사 할 수 있습니다.

예 :

로그인 엔드 포인트

[Route("api/Account/Login")] 
[HttpPost] 
public object Login(User userModel) { 
    User user = ...; 
    string token = CreateTokenForUser(user); 

    if (user != null) { 
     // return user and token back 
     return new {User = user, Token = token}; 
    } else { 
     throw new HttpResponseException(HttpStatusCode.Unauthorized); 
    } 
} 

사용자 정의 인증 필터

public class UserAuthAttribute : ActionFilterAttribute, IAuthenticationFilter 
{ 

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
    { 
     string token = null; 
     IEnumerable<string> tokenHeader; 
     if (context.Request.Headers.TryGetValues("Token", out tokenHeader)) 
      token = tokenHeader.FirstOrDefault(); 

     if (token != null && IsTokenValid(token) 
     { 
      // user has been authenticated i.e. send us a token we sent back earlier 
     } 
     else 
     { 
      // set ErrorResult - this will result in sending a 401 Unauthorized 
      context.ErrorResult = new AuthenticationFailureResult(Invalid token", context.Request); 
     } 
    } 

} 

인증 된 사용자 만 접근을 허용해야 다른 엔드 포인트

[Route("api/Values")] 
[HttpGet] 
[UserAuth] 
public object GetValues() { 

    // only requests with a valid token will be able to call this because of the [UserAuth] attribute 
} 
,
+0

몇 가지로 테스트 해 보겠습니다! 답변 주셔서 감사합니다! – CiucaS

+0

답변을 수락했습니다. 게시 한 내용 중 일부를 수정하여 일부 수정했습니다. 고맙습니다! – CiucaS

+0

해결책을 찾았습니다. 내가 게시 한 아이디어는 이미 작동중인 큰 프로젝트에서 온 것입니다 ... – ubi