所以我有一个调用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;
}
该认证是木已成舟调用的WebAPI方法
[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方法看起来像这样
[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应用程序和WebApi服务之间建立连接。我的授权和认证适用于MVC部分,但我的WebApi服务可以在没有任何授权/认证的情况下被调用。基于我的例子,我怎样才能保护我的WebApi?我一直在使用MVC和WebApi工作了大约3周,很多事情我也不太清楚。
我应该只是在公共IHttpActionResult登录(用户userModel)中创建一个GUID,并检查它每次我调用一个方法?我如何将这个GUID传递给MVC App,并从MVC传递给WebApi?
我会在几个测试!谢谢您的回答! – CiucaS
我已经接受了答案,我拿了一些你发布的内容并做了一些修改。谢谢! – CiucaS
很高兴听到您找到解决方案!我发布的想法是从一个已经运作的更大的项目... – ubi