ASP. NET MVC 5 Advanced Programming Chapter 7th Membership, authorization, and security

Source: Internet
Author: User
Tags oauth oauth provider openid csrf attack

Chapter 7th Membership, Authorization and Security 7.1 security

ASP. NET MVC provides a number of built-in protection mechanisms (by default, HTML encoding with HTML helper methods and razor syntax, and request validation, as well as the Controller Whitelist table unit built through the base architecture to prevent duplicate commit attacks)

Never trust any data submitted by users.

The actual example

    • Encodes a user's submitted data each time they are rendered.
    • Consider which parts of the site allow users to access anonymously, and which parts require authenticated access.
    • Do not attempt to purify the user's HTML input, otherwise it will fail.
    • Use the Http-only cookie when you do not need to access cookies through client script
    • Keep in mind that external input is not just an explicit form field.
    • It is recommended to use the ANTIXSS encoder.

Hackers, decryption gurus, spammers, viruses, malware--they all want to enter the data in the calculation read view. In reading this paragraph, our e-mail is likely to have forwarded many emails. Our ports have been scanned, and an automated worm is likely trying to find a way into the PC through a variety of operating system vulnerabilities. Because these attacks are automatic, they are constantly exploring and looking for an open system.

The application is built on the assumption that only certain users can perform certain operations, while others do not.

7.2 Logging in with the authorize feature

The first and easiest step in securing your application is to require users to log on to the system to access specific parts of the application. Authorize Attribute is a default authorization filter with ASP. NET MVC, which can be used to restrict user access to action methods.

Tips: Authentication and authorization

Authentication is the verification of a user's identity through some form of login mechanism (including user name/password, OpenID, OAuth, etc. that describe self-identity).

Authorization verification is used to verify that the user logged in to the site is performing operations within their permissions. This is usually implemented using some claims-based systems.

The authorize attribute takes no parameters and only requires the user to log on to the Web site in a certain role. It prohibits anonymous access.

7.2.1 Protection Controller operation

A good way to achieve security is to always keep the security check as close as possible to the object you want to protect. There may be other higher-level checks, but always ensure the security of the actual resources.

7.2.2 the use of authorize features in forms authentication and AccountController controllers

Basic authentication Information

        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;    

If the user authentication fails, a Httpunauthorizedresult operation result is returned, resulting in an HTTP 401 (unauthorized) status code.

7.2.3 Windows Authentication

To use the intranet authentication option, we need to enable Windows authentication and disable Anonymous authentication.

Secure your entire application with global authorization filters

The allowanonymous feature is newly added in MVC 4. If you register Authorizeattribute as a global filter, and some methods require external access, these methods only need to be decorated with the newly added allowanonymous feature in 4. AllowAnonymous is only valid for standard Authorizeattribute, and it does not necessarily work for custom authorization filters. Global Authorization is global only for MVC

7.3 Require role members to use the authorize attribute

The authorize feature allows you to specify roles and users.

The Roles parameter can have multiple roles, we use ', ' split:

7.4 Extended user Identity 7.4.1 Store user additional information

In Code first mode, you only need to add attributes to the user class.

7.5 External logins via OAuth and OpenID

OAuth and OpenID are open standards. These protocols allow users to log into our website using their existing accounts.

Configuring the Web site to support OAuth and OpenID is very difficult to implement and the Protocol is complex, and the top-level provider does not implement the two protocols in the same way. MVC simplifies this by using built-in support for OAuth and OpenID in project templates that use individual user Accounts authentication.

7.5.1 Registering an external login provider

Websites that use the OAuth provider require that we register the site as an application. This gives us a client ID and a password. We can use the OAuth provider to verify this information.

7.5.2 Configuring the OpenID Provider

Configuring the OAuth provider is straightforward because you do not have to register, and you do not need to fill in parameters.

7.5.3 Configuring the OAuth provider 7.5.4 External login security

1, Trusted external login

2, Require SSL login

The callback from the external provider to our site contains a security token that has user information that allows access to our website. When a token is passed over the Internet, it is important to use HTTPS transport because it provides access to information interception.

To access AccountController's login Get method and perform HTTPS, applications that support external logins should use the Requirehttps feature to use HTTPS

                //get:/account/login        [Requirehttps]        [allowanonymous]        pulic actionresult Login (String returnUrl )        {        viewbag.returnurl=returnurl;        return View ();        }    
7.6 Security vectors in WEB applications

Because Web applications run on top of standard, text-based protocols such as HTTP and HTML, they are particularly vulnerable to automatic attacks.

7.6.1 Threats: Cross-site scripting (XSS)

1, threat overview

There are two ways to implement XSS, one of which is to enter malicious scripts into the Web site, which in turn can receive "dirty" (unsanitized) user input. Another way to do this is by displaying the user's input directly on the page. The first case is called "Passive injection" (Passive injection). The user enters the "dirty" content into the text box, saves the data in the database, and then displays it again on the page. The second method, called "Active injection", involves the user entering the "dirty" content directly into the text box, and the input content is immediately displayed.

2, Passive injection

eg

        "></a><script src=" hackscript.js "></script><a href="    

3, Active injection

eg

      Http://www.meishizouqi.com? Search=<form action= "" ><input type= "text" name= "name"/><input type= "password" name= "password"/> <input type= "Submit" value= "Login"/>    

4, Block XSS

1) HTML encoding of all content

Each output on the page should be encoded by HTML encoding or HTML attributes.

2) Html.attributeencode and Url.encode

Remember: Never trust any data that users can access or use, including all form values, URLs, cookies, or personal information from third FountainVest partners (such as OpenID). In addition, the database or service accessed by the site may not be encoded, so do not trust any of the input application's data and encode it as much as possible.

3) JavaScript encoding

A hacker can randomly insert JavaScript script code into the input using the hexadecimal escape code.

4) Use the ANTIXSS library as the default encoder for ASP.

    • AntiXSS uses a white list of trusted characters, and ASP. NET implements a blacklist of limited untrusted characters by default.
    • The focus of AntiXSS is to block application vulnerabilities, and ASP. NET focuses on preventing HTML page display from being corrupted.

The. NET 4.5 and later versions contain the ANTIXSS encoder for MicroSoft WPL (Web Protection Library). To use the ANTIXSS library, you need to add the following code in the HttpRunTime of Web. config:< httpRunTime ... encodertype= " system.web.security.antixss.antixssencoder,system.web,version=4.0.0.0,culture=neutral,publickeytoken= b03f5f7f11d59a3a "/>

7.6.2 Threats: Cross-site request forgery

Cross-site solicitation forgery (Cross-site request FORGERY,CSRF, sometimes written xsrf) is more dangerous than a simple cross-site scripting attack.

1, threat overview

eg

The user exits the login method as:/account/logout

The user submits the comment to such a label

The browser will automatically send a GET request to that address.

2, stop CSRF attack

ASP. NET MVC provides a way to prevent CSRF attacks.

1) Token Verification

The Html.antiforgerytoken helper method generates an encrypted value as a hidden INPUT element.

This value matches another value that is stored as a session cookie in the user's browser. When the form is submitted, Actionfilter verifies that the two values match. This approach can block most csrf attacks.

2) Get request of idempotent

A idempotent operation is characterized by the same effect that is performed once and executed multiple times.

In general, simply modifying the contents of a database or website through post can effectively protect against all CSRF attacks.

3) Httpreferrer Verification

Httpreferrer authentication is handled by using Actionfilter. In this case, you can view whether the customer segment that submitted the form value is on the target site.

7.6.3 Threats: Cookie theft

If you can steal a person's authentication cookie on a website, you can impersonate him on that site and perform all actions within his authority. This attack relies on XSS vulnerabilities. An attacker would need to inject some script on the target site to steal cookies

stackoverflow.com allow a certain number of HTML tags to be included in a comment

You can stop the script from accessing the cookie in the site, and you need to set a simple flag: httponly

You can set all cookies in the Web. config file, or individually for each cookie you write.

7.6.4 threats: Repeating submissions

Duplicate commit: A malicious user adds a value that exceeds the user's final action permission to a query string or a submitted form.

One of the simplest ways to defend against duplicate submissions is to use the [Bind] attribute to explicitly control the properties that need to be bound by the model binder. You can also accept a binding list with an overloaded version of the Updatemodel or TryUpdateModel method.

7.6.5 Threats: Open redirection

1. Threat Overview

Web applications that point to redirected URLs through requests, such as query strings and form data, may be tampered with and redirect the user to an external malicious URL. This tampering is known as an open redirection attack (open redirection attack).

You can call the Islocalurl () method to validate the RETURNURL parameter.

7.7 Appropriate error reporting and stack traces

The customErrors mode has 3 optional settings, namely:

    • On: The server develops the safest option because it always hides the error message.
    • RemoteOnly: Displays generic error messages to most users, but displays complete error messages to users who have access to the server.
    • OFF: The most vulnerable option, which shows detailed error handling to visitors to each site.
7.7.1 Using Configuration transformations

Replace Customerror mode with RemoteOnly mode.

7.7.2 using the retail deployment configuration in a production environment

The deployment configuration is a simple switch in the next Machine.config file in the server environment to identify whether ASP. NET is running in retail deployment mode.

Setting Deployment/retail to True will affect the following settings

    • Set to ON, which is the safest setting
    • Disable trace output
    • disabling debugging

These settings can override all application-level settings in the Web. config file

7.9 Summary

Security issues in WEB applications can always be attributed to the simple problems of the developer side: improper assumptions, error messages, and lack of training.

ASP. NET MVC 5 Advanced Programming Chapter 7th Membership, authorization, and security

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.