Authentication and Authorization CS795/895

advertisement
Authentication and
Authorization
CS795/895
How .Net Security Works
• Users who log in to the application are granted a principal and an
identity, based on the credentials they have provided.
• Principal object: Represents the group or role membership of the
authenticated user, i.e. security context of the current user. It is
possible to create a generic principal object using data from a
database. Httpcontext.Current.User property returns an instance of
IPrincipal.
• Identity object represents the authenticated user. Windows
authentication uses WindowsIdentity while forms authentication
uses FormsIdentity object.
• http://www.developerland.com/Web/Security/215
.aspx
IPrincipal Interface
• HttpContext.Current.User property returns an
instance of IPrincipal
• It is part of System.Security.Principal
• Has a single property: Identity: Gets the IIdentity
of the current Principal: Example:
HttpContext.Current.User.Identity.Name
• Has single method: IsInRole(roleName As
String): Example: if
(HttpContext.Current.User.IsInRole(“Admin”)
{…..}
IIdentity Interface
• Provides current user’s identity
• Four identity classes included in .Net:
– System.Web.Security.WindowsIdentity
– System.Web.Security.FormsIdentity
– System.Web.Security.PassportIdentity
– System.Web.Security.GenericIdentity
Types of Authentication
•
•
•
•
Windows Authentication
Forms Authentication
Extending Forms Authentication
Custom Authentication
Windows Authentication
• Why this type?
• Little work for programmer
• Integrates well with IIS security
• Integration with windows client machine---no need
for a user to authenticate for an application if
already done so initially by the windows OS
• Why not this type?
• Tied to windows users
• Tied to windows client M/C
• Lack of flexibility
How does it work?
•
•
Internet Information Services (IIS) is a powerful Web server that provides a highly reliable,
manageable, and scalable Web application infrastructure for all versions of Windows Server.
IIS 8.0 is the latest version.
IIS uses three possible strategies to authenticate each request it receives:
• Basic authentication: Username and password in
clear text
• Digest authentication: Username and password
protected with digests
• Integrated windows authentication: The identity of
a user already logged in to Windows is passed
automatically, without user entering it again
Basic Authentication
• IIS obtains logon info from an HTTP client via the familiar
windows dialog box to obtain username and password
• The information is then transmitted to the web server
• It then attempts to login to the windows account with the
username and password
• It also checks if the account is allowed to access the
requested file/directory
• If successful, the response rendered by web server is
returned to the HTTP client
• Weakness: Username + password data between client
and server is encoded into a string that intruders may
have access to. So it is preferable to use if SSL-like
secure mechanism is used in between.
Digest Authentication
• Like basic authentication, it requires user
to enter username/password.
• Instead of sending the password in clear, it
sends a digest of the password.
• The HTTP client creates a hash value of the
password, the nonce sent by the HTTP server, and
some other values. This hash is the digest
• The HTTP server uses the stored password for the
username to generate the hash (digest) and
verifies it.
Integrated Windows Authentication
• Most popular among the simple authentication
schemes
• For users who have already logged into a
Windows machine
• Provides WAN or LAN based internet
applications with an authentication practice that
is virtually invisible to the user
• A domain controller provides user credentials to
the client station where user log in.
• These credentials are in turn transferred to the
IIS at the request server
Configuring ASP.Net to use
Windows Authentication
• In web.config, set <authentication mode =
“windows”>
• This creates a WindowsPrincipal object
and a WindowsIdentity object, with each
request
• User.Identity.Name provides user name
• WindowsPrincipal.IsInRole methods lets
us test if the user has a specific role
Forms Authentication
• Here, an HTML form is used for users to
enter their credentials
• Similar to cookie authentication---where
when a user’s credentials (username and
password) are verified, a cookie is set.
Subsequent requests use this cookie to
identify the user.
Why Use Forms Authentication?
• Keeps all authentication code within the
application
• We have full control over the appearance
of the login form
• Works for users with any browser
• Allows us to decide how to store user
information (by default stored in
web.config file but can be stored
anywhere)
Why not Forms authentication?
• We have to create our own interface for
users to log in
• We have to maintain user details
ourselves
• Resources protected by forms
authentication must be processed by
ASP.Net (i.e., anonymous access
bypassing ASP.Net is not possible)
How forms authentication works?
• When request is made to a page protected by forms authentication,
the user is redirected to a login page. The URL of the original
request is preserved.
• Login page contains a form for users to enter their credentials (e.g.,
username and password)
• If the details the user entered are correct, an “Authentication ticket”
is created. The ticket contains the encrypted details of the user. The
ticket is written into a cookie and sent to the client machine.
• The user is then redirected back to the URL they originally
requested. Now the authentication cookie is added to the request by
the browser and picked up by the authentication module.
• The URL authorization module uses the details to verify user and
provide access
Forms Authentication API
• FormsAuthenticationModule class: To do the
background work with the presented authentication ticket
or cookie (done automatically); HTTP module that works
in background
• FormsAuthentication class: Contains utility methods and
properties that we can use when implementing forms
authentication
• FormsIdentity: An implementation of IIdentity
• FormsAuthenticationTicket class: Represents the details
of a user that we will encrypt and write to the
authentication cookie.
• These are all in System.Web.Security namespace
Implementing Forms Authentication
• Step 1: Configure forms authentication in the web.config file:
<authentication mode = “forms”>
<forms name=“xyzApplication” --- unique name for the cookie
loginUrl=“secure/login.aspx” ---page to which user should be directed
timeout=“30”---length of time in minutes an authentication cookie is valid
Path=“/” ---path for the cookie for the browsers
Protection=“all” ---do both encryption and a MAC for the cookie
<credentials passwordFormat =“clear”>
<user name =“xyz” password=“dqunik” />
<username =“pqr” password = “ghwww” />
</credentials>
</forms>
</authentication>
Implementing Forms Authentication (Cont.)
• Step 2: Create a login form to enable users to enter their credentials
– Login.aspx HTML page that handles the entering and validating the user
name/password
– Login.aspx.cs class that has the business logic for the login.
private viod LoginButton_Click(0bject sender, System.EventArgs s)
{//Check credentials
If (FormsAuthentications.Authenticate
(UserNameTextBox.Text, passwordTextBox.Value))
{FormsAuthentication.RedirectFromLOginPage
(UserNameTextBox.Text, false);}---not a persistent cookie
Else
{ErrorMessageLabel.Visible= true;}
• Later: More on other Authentication
features
• http://www.ondotnet.com/pub/a/dotnet/2003/01/06/formsauthp1.html
Implementing Authorization
• Granting access to resources using user names
or roles
• Roles are similar to groups in Unix and Windows
• Application may define its own roles or use
Windows roles
• In ASP.Net, the authorization starts from what
ASPX pages the user is allowed to access
• ASP.Net provides some generic types of
solutions: E.g., File Authorization, URL
Authorization, and Custom Authorization
How Identity and Principal are
used?
• Types of identities (as we have already seen), depending on
authentication used: WindowsIdentity, FormsIdentity,
PassportIdentity, GenericIdentity
• All these implement IIdentity interface (part of
System.Security.Principal namespace)
• An application may always find the user attached to the current
thread using Identity object
• Principal: a combination of user and groups the user belongs to
(Identity+roles)
• Principal types: WindowsPrincipal and GeneraicPrincipal
• Both implement IPrincipal interface (part of
System.Security.Principal namespace)
• IPrincipal (as discussed before) provides the following:
• IIdentity Identity (get): to get the underlying object
• IsInRole(string role): to determine whether the user belongs to a certain role
Role-based Security
• In general, authorization requirements are as follows:
– Users should have proper credentials to access a resource
– Certain users need to be denied access to particular resources
– Only certain users should be allowed to access particular
resources
• If you intend to use RBS, you must either assign an
IPrincipal to a thread manually or configure the runtime
to create one automatically
• Use System.AppDomain.SetThreadPrincipal to
automatically generate for each thread, or
– Set current thread’s IPrincipal manually using
System.Thredaing.Thread.CurrentPrincipal property.
Making Role-based Security
Demands
• Do not result in a stack walk---based solely on identity and roles of
the active thread’s principal
• Imperative role-based security statements:
– Commonly used constructor: PrincipalPermission
– Each PrincipalPermission can specify only a single role name.
“null” means no matching is needed
– Public PrincipalPermission(string name, string role)
PrincipalPermission p1 = new PrincipalPermission(“John”, “Manager”);
p1.Demand();
PrincipalPermission p2 = new PrincipalPermission(null, “Programmer”);
p2.Demand();
PrincipalPermission p3 = new PrincipalPermission(“Kevin”, null);
p3.Demand();
PrinciplaPermission Explanationhttp://msdn.microsoft.com/enus/library/system.security.permissions.principalpermission.aspx
• Using Declarative role-based security
statements:
– PrincipalPermissionAttribute may be applied to
classes, methods, properties, or events to force
declarative demands
– This cannot be applied at the assemble level
– Demand, LinkDemand, and InheritanceDemand are
the only RBS statements allowed
[PrincipalPermission(SecurityAction.Demand, Name=“John”, Role=“Manager”)]
[PrincipalPermission(SecurityAction.Demand, Role=“Programmer”)]
[PrincipalPermission(SecurityAction.Demand, Name=“Kevin”)]
File Authorization
•
•
•
1.
2.
FileAuthorizationModule class uses the underlying ACLs of the
file system to control access to ASPX pages
This works only in conjunction with Windows Authentication
Example:
Create a new web application. Name the form Index.aspx
Place the following code under the <form> tag:
<a href =“AuthorizedFile.aspx”> Click here for AuthorizedFile </a> <br>
<a href =“UnAuthorizedFile.aspx”> Click here for UnAuthorizedFile </a>
3. Add two new web forms: AuthorizedFile.aspx and UnAuthorizedFile.aspx
4. Under <form> tag in AuthorizedFile type: <h2> You have access to the file </h2>
Under <form> tag in UnAuthorziedFile type: <h2> You do not have access to the file </h2>
5. Build the solution and run: Clicking the links, the messages will appear
6. Create three different users: user1, user2, user3
7. Provide the following access rights to UnauthorizedFile.aspx: user1: Full access; user2: Read and
Execute; user3: Deny All
8. Login as user3 and click on UnAuthorizedFile link; it will be denied access
URL Authorization
Authorization section in web.config
<authorization>
<allow users=“john,jim,kevin”
roles=“programmer,manager” verbs
=“GET,PUT”/>
<deny users=“?” />
? Anonymous users; * all users
• Authorization for a specific file or folder (using
web.config):
<location path=“UnAuthorizedFile.aspx”>
<system.web>
<authorization>
<deny users = “\localhost\user3” />
</authorization>
</system.web>
</location>
(This overrides what the OS says about the permissions)
Calculation of Permissions
• The default permission is to allow access for all users
• Upon calculation of a merged rule set, the system checks the rules
until it finds a match: either allow or deny
• When a deny is encountered, the system throws a 401 error:
Unauthorized access
• Example:
At the application level, include in web.config: <authorization> <allow
users=“localhost\user1, \localhost\user2” /> <deny users = “?”/>
</authorization>
At a particular page level, we can add this to web.config:
<location path=“UnAuthorizedFile.aspx”> <system.web>
<authorization><deny roles = “users” /> </authorization>
</system.web> </location>
Denies access to this page to any windows user.
Authorization Checks in Code
• We can control access even at a button level
using checks in the code
• If {user1, user2} are made into a single group
called validgroup, then:
if
(Thread.CurrentPrincipal.IsInRole(“localhost\vali
dgroup”))
{Response.Write (“You have access”);}
else
{Response.Redirect(“AuthorizationError.aspx”);}
Demanding Credentials
try
{ PrincipalPermission pp = new PrincipalPermission(“user1”, “validgroup”);
pp.Demand();
Response.Write(“PrincipalPermission successful”);
}
Catch (SecurityException se)
{Response.Write (“PrincipalPermission Denied”);
}
Merging PrincipalPermission objects:
try
{PrincipalPermission pp1 = new PrincipalPermission(“user1”, “validgroup”);
{PrincipalPermission pp2 = new PrincipalPermission(“user2”, “validgroup”);
{PrincipalPermission pp3 = (PrincipalPermission)p1.Union (p2);
pp3.Demand();
Response.Write(“PrincipalPermission successful”);
}
Catch (SecurityException se)
{Response.Write (“PrincipalPermission Denied”);
}
PrincipalPermissionAttribute:
Another way to Authorize
• Place the following code above the
method declaration:
[PrincipalPermissionAttribute(SecurityAction.Demand, Name=“user1”,
Role = “validusers”)]
Or
[PrincipalPermissionAttribute(SecurityAction.Demand, Role =
“validusers”)]
Custom Authorization
• To be discussed later
Download