繁体   English   中英

使用Web API的C#自定义授权

[英]C# Custom authorization with Web API

我正在设计一个WebAPI项目,而我的第一个控制器是LoginController。 用户登录如下:

    [ActionName("Login")]
    [AcceptVerbs("PUT")]
    [HttpPost]
    public HttpResponseMessage Login(DTO.LoginDetails loginDetails)
    {
        HttpResponseMessage response = null;
        DTO.User user = null;

        try
        {
                string connectionString = string.Empty;

                //Login the user
                user = Mapper.Map<DTO.User>(loginService.Login(loginDetails.Username,
                                                               Md5.Encrypt(loginDetails.Password));

                if (user != null)
                {
                    //Create session for the user
                    DTO.Session session = new DTO.Session()
                    {
                        User = user,
                        Token = Guid.NewGuid().ToString()
                    };

                    //Create collection to store the cookie values
                    var nv = new NameValueCollection(3);
                    nv[SessionHandler.UserId] = user.Id.ToString();

                    //Create a cookie
                    var cookie = new CookieHeaderValue(SessionHandler.Session, nv)
                    {
                        Expires = DateTimeOffset.Now.AddDays(1),
                        Domain = Request.RequestUri.Host,
                        Path = "/"
                    };

                    response = Request.CreateResponse<DTO.Session>(HttpStatusCode.OK, session);
                    response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                }

                //Login failed
                else
                {
                    response = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("User or connectionstring is null or empty"));
                }
            }
        }
        catch (Exception ex)
        {
            response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            logService.Logger().Error("Login failed", ex);
        }

        return response;
    }

我也有一个DelegatingHandler,它从每个请求中获取上述cookie。 目前,它只是从请求中获取Cookie。

用户存储在数据库表中,并根据该表进行验证。 表格中的每个用户都有4个显式权限(CRUD),以确定他是否可以对实体(客户,产品等)执行操作。

所以我的问题是:

  1. 成功登录后将用户存储在MemoryCache中是一个好主意,这样可以避免往返数据库以验证用户是否已通过身份验证?

  2. 如何使用自定义的Authorize属性来确保用户有权对实体执行操作? 此代码应该在控制器级别还是服务级别?

  3. Login控制器装饰有[AllowAnonymous],而其他所有控制器则没有。 但是我的DelegatingHandler是系统范围的。 我应该将控制器移到自己的区域中,还是将登录控制器留在主区域中?

  1. 当然。 最好让用户缓存并首先从缓存中获取用户,如果错过了,再从数据库中获取用户(通过存储在cookie和db中的密钥-如LastSessionId)。
  2. 最好是User(或代码中的Session)类从GenericPrincipal接口派生并重写/添加一些代码来管理Roles集合。 因此IsInRole方法将为您工作(由AuthorizeAttribute使用)。 IUserPrincipal是您自己的界面,用于添加所需的行为/数据。 因此,不管它是自定义属性,还是它都可以在控制器级别正常工作

      class UserPrincipal : GenericPrincipal, IUserPrincipal 
  3. 我觉得不行 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM