Reputation: 18906
this a question from some MCTS 70-515 Exam Practice tests.
please help with the correct 2 answers
You are implementing an ASP.NET MVC 2 Web application that allows users to view and edit data. You need to ensure that only logged-in users can access the Edit action of the controller. What are two possible attributes that you can add to the Edit action to achieve this goal?
(Each correct answer presents a complete solution. Choose two.)
Upvotes: 2
Views: 2451
Reputation: 14941
Edit: I have changed this so it's now correct and just supplements dknaack's correct answer
Decorating an action with [Authorize]
means that the user must be authenticated.
So if you want any logged-in user to be able to access an action it's normal just to put [Authorize]
.
dknaack has referred to the source code, so his answer must be correct, even though it seems slightly strange to me. But clearly right!
Just to add, if _usersSplit
is like a normal split on comma then we'd expect _usersSplit.Length
to be 1
when _users =""
and I'd still be right, but I guess the split function is using the RemoveEmptyEntries
option. Can't refer to the source for that as am afk right now (had knee operation yesterday, not allowed on computer just yet - lol).
Empty string is not a valid name for a user or a role. See here: http://msdn.microsoft.com/en-us/library/8fw7xh74(v=VS.100).aspx
You should throw an ArgumentException if any of the specified user names or role names is an empty string and an ArgumentNullException if any of the specified user names or role names is null (Nothing in Visual Basic).
Upvotes: 2
Reputation: 60466
A look at the source code of the AuthorizeAttribute
shows that there is no wildcard "*".
It makes no sense if [Authorize(Users = "")]
would result in "no one" can access the action.
Source code of the AuthorizeAttribute
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;
}
And the Role
and Users
propertie.
public string Roles {
get {
return _roles ?? String.Empty;
}
set {
_roles = value;
_rolesSplit = SplitString(value); // simple split by comma
}
}
public string Users {
get {
return _users ?? String.Empty;
}
set {
_users = value;
_usersSplit = SplitString(value); // simple split by comma
}
}
Upvotes: 6