Web上的基本令牌验证和授权.Api

时间:2016-09-06 08:54:29

标签: c# asp.net-mvc authentication asp.net-web-api authorization

所以我有一个调用WebApi方法的MVC应用程序。

我在MVC App上的授权是这样完成的

  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 App和WebApi Services之间建立连接。我的授权和身份验证适用于MVC部分,但我的WebApi服务可以在没有任何授权/身份验证的情况下调用。我如何根据我的例子保护我的WebApi?我已经和MVC以及WebApi一起工作了大约3个星期,很多事情我也不是很清楚。

我应该在公共IHttpActionResult Login(User userModel)中创建一个GUID并在每次调用方法时检查它吗?如何将此GUID传递给MVC App并从MVC传递给WebApi?

1 个答案:

答案 0 :(得分:2)

您可以做的是在WebAPI Login()方法中创建某种令牌(例如JWT)并使用Ok()响应返回(到MVC应用程序)。调用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
}