简体   繁体   中英

Authentication and Authorization in MVC

I have created an asp.net web application with MVC. So far everything is good except authentication and authorization.

I want to do this: Create an authentication function and pass the username and password to it.

I already created the stored procedure which returns true or false. The authentication function just calls the procedure and returns true or false - if it returns true the user will be authenticated and we are good to go.

The next step is to have an authorization method which runs when the user wants to do anything (checks when user click on a button or link).

So I created an authorization function and pass the username and a function ID to it. Just like the authentication function, a stored procedure returns true or false. True means user can do it otherwise the user must return to the login page.

My questions are:

1- how can I run the authorization function whenever the user wants to do anything?

2- how can define a unique function ID? I mean function ID should be what? (objects ID?)

1 run authoristion function whenever the user wants to do anythng

Add an ActionFilterAttribute and apply it to all your controllers

2 give each function a unique id

No need, each function already has a unique name: controller name + action name (unless you have some very weird, unmanageable setup...)

Example:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AuthoriseActionAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var user = HttpContext.Current.Request.LogonUserIdentity;
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var action = filterContext.ActionDescriptor.ActionName;

        // call existing authorisation function here
        // using user, controller, action to determine if user has access
        bool authorised = ...

        if (!authorised) {
            // throw exception or redirect
            throw new UnauthorizedAccessException("You are not authorised to perform this action.");
        }

        base.OnAuthorization(filterContext);            
    }
}

usage:

[AuthoriseAction]
public class HomeController : Controller 

Note: I use windows authentication, so the user= part may not be what you need for your application authentication method. But the principle is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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