Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - How to use authorize attribute on MVC3

I've read that to use the attribute [Authorize] on MVC, you just have to place it over an action or over the controller class you want to secure.

My question is: How does the Authorize attribute know if a user is logged or not? Do i have to provide any Session object in order to let Authorize know if a user is authorized?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This attribute works by looking at HttpContext.User.Identity.IsAuthenticated.

If you're using something like FormsAuthentication, this will be set to true if the user has a valid FormsAuthentication cookie on their machine (which you can add by using FormsAuthentication.SetAuthCookie).

If you're interested in the inner-workings of Authorize, this is from the published Microsoft source code:

protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        } 

        IPrincipal user = httpContext.User; 
        if (!user.Identity.IsAuthenticated) { 
            return false;
        } 

        if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
            return false;
        } 

        if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) { 
            return false; 
        }

        return true;
    }

Here is some more info on FormsAuthentication.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...