1

I've currently got a very simple setup running. This setup consists of an entity-framework project, and an IIS server. The IIS is configured to use windows authentication.

Now in my project, I want to allow only certain users to gain access to certain controllers. Within the organisation I'm working for there's a "permissions" system, a table that contains what users are allowed to access what data. So, I want to get the e-mail with which the user logged in, and check that against the database to see if he has permission.

My plan for doing this was to make a seperate piece of code, that's not accessable from the web, that contains the function "boolean hasPermissions(String email, byte permissions)". But I've got no idea where to place this, nor can I find any information on this. Is what I have in mind the right approach? And if, then how to execute this approach correctly?

1 Answer 1

1

You should use windows authentication, using IPrincipal , you will have a user object that you could ask IsInRole for specific role based security instead of bits / booleans

read all about it at Asp.net windows authentication

and how to implement IPrincipal Implement custom security

Code sample: User object:

public class User : IPrincipal
{
    private readonly IPrincipal _user;
    public IIdentity Identity { get; private set; }

    public User (IPrincipal user)
    {
        Identity = user.Identity;
        _user = user;

    }

    public bool IsInRole(string role)
    {
        return _user.IsInRole(role);
    }
}

In MVC add a filter

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
    {

        public void OnAuthentication(AuthenticationContext filterContext)
        {

            var user= new User (HttpContext.Current.User);
            Thread.CurrentPrincipal = user;
        }

  }

And add that filter to your FilterConfig using

filters.Add(new CustomAuthenticationAttribute());

Then, when using the user object within your application

var user = new User(Thread.CurrentPrincipal); 
if(user.IsInRole("admin")) /* do the choka choka */;
Sign up to request clarification or add additional context in comments.

2 Comments

I have got the idea you are indeed right, and that is what I need. However, I've been looking around the last two hours now, and I've got no idea on how to implement this. Would you have any code examples for me? Mainly on how to get the user object and where to put the authentication code.
Thank you so much. I made an edit suggest that contains the adaptions I had to make to get it working. This for future newcomers like me who have no idea what does what.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.