Skip to content

Authorize a client and SecurityContractAttribute

Ali Yousefi edited this page Jan 10, 2020 · 2 revisions

Before reading this document learn how to use OperationContext CurrentSetting

With the SecurityContractAttribute you can Authorize your clients on the server-side and make custom rules and everything you want to do for Authentication.

An example to use SecurityContractAttribute is easy:

First, You have to create a class and inheritance SecurityContractAttribute like this:

 /// <summary>
    /// my custom security attribute
    /// </summary>
    public class ExpertSecurityPermissionAttribute : SecurityContractAttribute
    {
        /// <summary>
        /// just admin users can access to the service
        /// </summary>
        public bool IsAdmin { get; set; }
        /// <summary>
        /// just normal users can access to the service
        /// </summary>
        public bool IsNormalUser { get; set; }
        
        public override bool CheckPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters)
        {
            //get current user
            var data = OperationContext<CurrentUserInfo>.CurrentSetting;

            //user is not loggined
            if (data == null)
                return false;
            //user is admin and service access is for admin users too
            else if (data.IsAdmin && IsAdmin)
                return true;
            //user is normal and service access is for normal users too
            else if (data.IsNormalUser && IsNormalUser)
                return true;
            return false;
        }

        public override object GetValueWhenDenyPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters)
        {
            //return everything you want to send to the client when permission denied.
        }
    }

Second, write your logic for check permission in the CheckPermission method, if you return false then SignalGo will automatically call GetValueWhenDenyPermission and send the result to the client if you return true SignalGo will call your method because the client has permission.

Example of use over Methods:

        [ExpertSecurityPermission(IsNormalUser = true)]
        public MessageContract EditUserInfo(UserInfo userInfo)
        {
        }