Java Web Basics Security: Life is short, pay attention to safety

Source: Internet
Author: User
Tags http authentication http digest authentication md5 hash tomcat server

About the security aspects of the Web program, presumably most people do not understand, or feel that there is no need to understand, around the development of the site is mainly focused on the background of the function and front-end interface, do not say that the security of the program, or even the background database access problems may not be under the strong gas solution. But this is closely related to our problem, every day to see the site which system or site security issues are feeling very far away from their own, in fact, this is just an illusion, or that sentence-life is too short, pay attention to safety (some people do not understand the wrong, said is you. )。 Write this article, just think of this cock Silk Test University newspaper volunteer time, then Bupt opened a professional called information security, that era is not very fire, but by virtue of this Dick sharp insight (in fact, feelings) at a glance out of the professional prospects, but unfortunately is just opened, not enrolled ... Sorry Ah!!

Protecting our web programs can be done in both declarative and programmatic ways, but in either case, the 4 aspects of web security are met:

    • Verification: This is the most familiar to us, every start to develop a Web application will be a login page, which is actually to verify the identity of Web users, the Web users here is not necessarily a person, or a program, such as some crawlers want to crawl some pages, which requires them to provide a user name and password;
    • Authorization: About this should also be familiar with, but because we are not too concerned about, causing the neglect of this point, it is mainly concerned about the level of the authenticated user, is in the last step after verification success, it is used to restrict a user has access to a part of the Web program, intuitive Point said, A website has the ordinary user, also has the administrator, what content edits and so on, although they can log on successfully, but the ordinary user and the page edit is unable to enter the website management interface, this is that they did not obtain the website owner's authorization, here realizes the way is through establishes the role to complete, gives each person specific role , and then specify which parts of the Web program a role can access, and recently Facebook rewarded $10,000 for a 10-year-old child who discovered an Instagram vulnerability, or a licensing vulnerability.
    • Encryption: This is better understood, because the data is transmitted from the Internet when the transfer from one computer to another computer, waiting for the server, it may have passed more than one computer, which gives others to intercept the data provides a great convenience, so we need to encrypt the transmitted data, About the encryption algorithm there are many, Mu class online has a lot of encryption algorithm explanation, you can go to see;
    • Complete: About the integrity of the data, in short, although you encrypt the transmission of data, but people can still intercept, may just read not understand what the meaning, but can be arbitrarily changed, to the receiver will not be able to confirm that the data is still sent from the client data, so there is no guarantee of data integrity, Like digital circuits there are parity bits to ensure the correct data transmission, in the Web program can be established by establishing a secure channel to transfer data.
Do you use declarative or programmatic security management for Web applications? In fact, it depends on the specific business requirements, each of them two each has its advantages and disadvantages:
    • Programming: In fact, most Web applications are used in this way, we do not have to read this article all know how to do, the user entered the user name and password and stored on the server or database to verify, if the verification is successful, then look at the specific role of the customer.
    • Disclaimer: The greatest benefit is to avoid partial programming because the validation and authorization part is done by the servlet container, and in declarative security, the browser can encrypt the user name and password before sending it to the server, so all security constraints are not written to the Servlet class due to the use of the Declaration. As long as the declaration in the deployment descriptor, there is a lot of flexibility, but there are drawbacks to declaring this way, the authentication method that supports data encryption can only use the default login box provided by the servlet container (Tomcat), cannot be customized, in this face society has undoubtedly been eliminated, In addition, if you want to use a custom login form, the transmitted data will not be encrypted.
Declarative security actually uses the content in the HTTP protocol using declarative authentication, not the content in the servlet (the HTTP feature is simply too powerful). With declarative security, the first thing to do is to define users and roles, different servlet containers, where users and roles are saved, and use Tomcat to save this information in the profile tomcat-users.xml, and then to make security restrictions on some resources. The configuration in Tomcat-users.xml is as follows:
<role rolename= "Manager-gui"/><role rolename= "admin"/><role rolename= "user"/><user password= " Tomcat "roles=" Manager-gui "Username=" Tomcat "/><user password=" lmy86263 "roles=" admin "username=" lmy86263 "/ ><user password= "Guest" roles= "User" username= "Guest"/>
When configuring Tomcat users and roles, be aware that each time you restart Tomcat, the users and roles you have previously configured will disappear to the default state of Tomcat, because when you first configure the Tomcat server in Eclipse, Eclipse will copy the Tomcat configuration file to the server folder under its own workspace, each time the read profile is read from here, and the configuration file under the Tomcat directory is overwritten with this configuration, so in order to avoid this kind of trouble, We will copy the configured files to the server folder under Workspace, as follows:
You can hide files in the Web program under Web-inf or in their subdirectories, but in the background you can jump there through servlets and JSP pages, simply rude and not good enough. We can validate requests to access these resources by placing them in the application directory and then using security constraints, primarily by configuring them in the deployment descriptor to implement constraints on some requests. Using Security-constraint and Login-config two elements in the deployment descriptor to complete the validation of access, the following three types are just a few of the properties of the transformation. Use the following:
<security-constraint><web-resource-collection><web-resource-name>httpservlet</ web-resource-name><url-pattern>/myhttpservlet</url-pattern>
Some of the above elements are explained as follows:
    • Security-constraint: Used to specify a collection of resources and one or more roles that can access those resources.
    • Web-resource-collection: Used to specify a set of resources, there are several elements that are more important, Url-pattern will not say, and before using the servlet and filter, just to map a servlet resource, The mapping here only applies to direct access to the resource, if it is a background forward the resource or using a JSP tag to access without the security mechanism constraints, this element can have multiple; the Http-method element is used to define the HTTP method. For example, the Get and post methods described above illustrate that security constraints apply only to these two methods, that is, if using a put or Delete method to access these resources is not constrained by the security mechanism, the default is that all methods are protected, this element can also have multiple There is also an element that is not written here is http-method-omission, which is exactly the opposite of Http-method, which is to show that all methods except the method in this property will be restricted when accessing the resource, and it cannot be used with Http-method;
    • Auth-constraint: Used to specify the name of a role that can access the resource, which means that the element is accessible to everyone if it is not present, which makes no sense; if the element exists but is empty, it means that no one has direct access to the resource (note directly);
1, basic access authentication is to accept the user name and password HTTP authentication, if the user accesses a protected resource, it will be rejected by the server, the login box will persist until you enter the correct user name and password, if you cancel the authentication will return 401 error, However, it is important to note that if you log in successfully, but your role-name does not appear in <auth-constraint>, it will return a 403 error, so be aware that the two errors are different.
<login-config><auth-method>basic</auth-method><realm-name>admin only</realm-name> </login-config>
The use of this HTTP authentication method, is the user name and password in accordance with the "User name: Password" This form of combination and use the BASE64 algorithm to encode the transmission to the server, the algorithm is very weak, on the internet to find a decoded website can know your user name and password. The following implementation occurs when there is a validation error and no authorization:validation Error:
Note the status code, and note that the HTTP protocol provides the first www-authenticate, you can see that the value in this is the property we configured above, this header is used to verify the identity of the program user, in which the realm contains the name of the role can access the resource, Another header authorization is used when logging in to contain user name and password information encoded with BASE64, as shown here, because the header was not sent because the validation was canceled. Note the order of the two headers, when the login request is issued using authorization, and then the server returns Www-authenticate, but when you cancel the login you will also return www-authenticate, in short, You will return to this header as long as you have not logged in successfully.No authorization:
As you can see here, the validation is successful, but because the user's corresponding role is not within the scope of the security constraint, it is also forbidden to access the resource. 2. Summary access validation is similar to digest access validation and basic access validation, except that the validation method uses digest, which does not use the BASE64 algorithm. This is a hash value that uses the MD5 hash function to calculate the combination of user name, password, realm value, and then send the hash value to the server, where the specific technique is shown below.
<login-config><auth-method>digest</auth-method><realm-name>admin Only</realm-name ></login-config>

Requests and responses using this method are as follows:


3. Form access verification because neither of these methods can support a custom login page, using form-based access validation avoids this embarrassment, but because the data transferred in this way is not encrypted, its use is used in conjunction with other cryptographic methods such as SSL. In this way, the first thing to do is to customize the login page and error handling page, using the form to verify the configuration with the following declaration:
<login-config><auth-method>form</auth-method><realm-name>admin only</realm-name> <form-login-config><form-login-page>/login.jsp</form-login-page><form-error-page>/ Error.jsp</form-error-page></form-login-config></login-config>
When the user name and password are not the same as the database or the information stored in the file will return to the Error.jsp page, if the match is successful will not return the page, if the successful match, but the user's role does not have permission to access the page, will not return the error.jsp page, but directly return 403 no access information. The error handling page is relatively simple here is not explained, but there are a few points in the login page to note that the login page is as follows:
<%@ page language= "java" contenttype= "text/html; CHARSET=GBK "    pageencoding=" GBK "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
In the form, noteThe action is J_security_check, the user name is J_username, the password is J_password, and these three fields are implemented by a servlet container ., Tomcat is used here, the class that handles this part in Tomcat is Org.apache.catalina.authenticator.FormAuthenticator, and the corresponding code is in the Authenticate () method, as follows:
    Boolean loginaction = (Requesturi.startswith (contextpath)) && (Requesturi.endswith ("/j_security_check"));      if (!loginaction) {if (Request.getservletpath (). Length () = = 0) && (request.getpathinfo () = = null))        {StringBuilder location = new StringBuilder (RequestUri);        Location.append ('/');          if (request.getquerystring () = null) {location.append ('? ');        Location.append (Request.getquerystring ());        } response.sendredirect (Response.encoderedirecturl (location.tostring ()));      return false;      } session = Request.getsessioninternal (true);      if (log.isdebugenabled ()) {Log.debug ("Save Request in Session '" + session.getidinternal () + "'");      } try {saverequest (request, session);        } catch (IOException IoE) {log.debug ("Request body too big to save during authentication"); Response.senderror (403, sm.getstring ("Authenticator.requestbodytooBig "));      return false;      } forwardtologinpage (Request, Response, config);    return false;    } request.getresponse (). Sendacknowledgement ();    Realm realm = This.context.getRealm ();    if (this.characterencoding! = null) {request.setcharacterencoding (this.characterencoding);    } String username = request.getparameter ("J_username");    String Password = request.getparameter ("J_password");    if (log.isdebugenabled ()) {Log.debug ("authenticating username '" + username + "'");    } principal = Realm.authenticate (username, password);      if (principal = = null) {forwardtoerrorpage (request, Response, config);    return false;    } if (log.isdebugenabled ()) {Log.debug ("Authentication of '" + Username + "' was successful");    } if (session = = NULL) {session = Request.getsessioninternal (false);  } if (session = = null) {if (this.containerLog.isDebugEnabled ()) {This.containerLog.debug ("User took so Long to log on the session expired ");      } if (this.landingpage = = null) {Response.senderror (408, sm.getstring ("authenticator.sessionexpired"));        } else {String URI = Request.getcontextpath () + this.landingpage;        Savedrequest saved = new Savedrequest ();        Saved.setmethod ("GET");        Saved.setrequesturi (URI);        Saved.setdecodedrequesturi (URI);                Request.getsessioninternal (True). Setnote ("Org.apache.catalina.authenticator.REQUEST", saved);      Response.sendredirect (Response.encoderedirecturl (URI));    } return false; }
Second, programming security now most applications are actually using this approach to achieve their own security requirements, fortunately in the servlet already have this aspect of the specification, let us very easy to use. But one thing that is not done is that although it is not declared in the configuration file, the login page to be performed while validating is still to use the Login-config configuration in Web. Xml. 1, the use of annotations when using annotations in fact, the completion of the Security-constraint in Web. XML is the function of the security-related mainly three annotations:
    • @ServletSecurity: Includes the following two annotations, corresponding to the security-constraint element;
    • @HttpConstraint: Used primarily to add a role that allows access to the resource through rolesallowed configuration;
    • @HttpMethodContraint: Mainly used to add the HTTP method that is restricted by the security mechanism, it also has a rolesallowed property, and the above annotation in the attribute to express the same meaning, but it is only used;
The use of the latter two annotations can evolve a lot of combinations, simple to use as follows:
@WebServlet (name= "Securityservlet", urlpatterns={"/securityservlet"}) @ServletSecurity ([email protected] ( rolesallowed= "User"), httpmethodconstraints={@HttpMethodConstraint (value= "GET", rolesallowed= "admin") public Class Securityservlet extends HttpServlet {}
Description allows the user role to access the resource using all HTTP methods except the Get method, but when accessing the resource through the Get method, you must verify that the client's role is admin. You can refer to the following articles for a variety of combinations and specific meanings of these annotations.
2, using the API in addition to using annotations, the servlet specification also provides programmatic security using APIs, which are defined in HttpServletRequest and are used as follows:
    • Getauthtype (): Returns the validation method that protects the servlet, corresponding to the value of <auth-method> in <login-config> in Web. XML, and returns null if no validation method is used;
    • Getremoteuser (): Returns the login name of the user who made the request and returns NULL if the user does not pass validation;
    • IsUserInRole (): Indicates whether the authenticated user belongs to the specified role, and if not verified, returns false;
    • Getuserprincipal (): Returns the Java.security.Principal containing the authenticated user information, or null if not verified;
    • Authenticate (): The command browser displays the login window used to authenticate the user, validate the method using form when the login window is our custom form, otherwise use the servlet container to provide us with the login window;
    • Login (): Used to provide user name and password to log in, login success does not return any value, login failure will throw servletexception;
    • Logout (): Reset user information;
Examples of usage are as follows:
@Overrideprotected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { if (Req.authenticate (resp)) {System.out.println ("Success");} else {System.out.println ("fail");} System.out.println ("authtype:" + req.getauthtype ()); System.out.println ("RemoteUser:" + req.getremoteuser ()); System.out.println ("IsUserInRole:" + req.isuserinrole ("admin")); System.out.println ("Userprincipal:" + req.getuserprincipal ());}
The form validation method is used here, so the forms we use are custom-defined. When validation succeeds, the output is as follows:
When validation fails, the output is as follows: Overall, the servlet-provided security-oriented programming model is still very handy, much larger than the information we save by directly validating the database.
Related articles:
    • With regard to web security, 99% of Web sites have ignored these
    • Tomcat keeps resetting my tomcat-users.xml file
    • Web. XML and four types of authentication
    • HTTP Digest Authentication
    • Programmatic Security Policy configuration

Java Web Basics Security: Life is short, pay attention to security

Related Article

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.