java Notes: Spring Security Applications

Keywords: JSP Spring Java xml

The first thing to mention in the Java project is the jar package, the jar download address of Spring Security: http://static.springsource.org/spring-security/site/downloads.html . However, the jar package in my project is rather old and extracted from previous projects. My engineering structure drawings are as follows:

First example:

The first example is the most basic and simplest. When I first came into contact with spring security, I thought it was amazing, but that's what it feels like now.

The first thing I wrote was web.xml:

<?xml version="1.0" encoding="UTF-8"?>  
02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
03.xmlns="http://java.sun.com/xml/ns/javaee"   
04.xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
05.xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
06.id="WebApp_ID" version="2.5">  
07.  <display-name>SpringSecurityPrj</display-name>  
08.  <context-param>  
09.    <param-name>contextConfigLocation</param-name>  
10.    <param-value>  
11.        classpath:applicationContext*.xml  
12.    </param-value>  
13.  </context-param>  
14.  <filter>  
15.    <filter-name>springSecurityFilterChain</filter-name>  
16.    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
17.  </filter>  
18.  <filter-mapping>  
19.    <filter-name>springSecurityFilterChain</filter-name>  
20.    <url-pattern>/*</url-pattern>  
21.  </filter-mapping>  
22.  <listener>  
23.    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
24.  </listener>  
25.  <welcome-file-list>  
26.    <welcome-file>index.jsp</welcome-file>  
27.  </welcome-file-list>  
28.</web-app>  

Next up is the application Context-security.xml file:

schemaLocation="http://www.springframework.org/schema/beans   
06.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
07.        http://www.springframework.org/schema/security  
08.        http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
09.    <!-- Automatic configuration mode, intercept all requests, there are ROLE_USER Only then can it pass through -->  
10.    <http auto-config="true">  
11.        <intercept-url pattern="/**" access="ROLE_USER"/>  
12.    </http>  
13.    <!-- Authentication Manager. User name and password are integrated in the configuration file -->   
14.    <authentication-manager>  
15.        <authentication-provider>  
16.            <user-service>  
17.                <user name="sharp" password="sharp" authorities="ROLE_USER"/>  
18.            </user-service>  
19.        </authentication-provider>  
20.    </authentication-manager>  
21.</beans:beans>  

In addition, I created a new index.jsp file, which is used to return to the index.jsp page after successful login:

[java] view plain copy 
01.<%@ page language="java" contentType="text/html; charset=UTF-8"  
02.    pageEncoding="UTF-8"%>  
03.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
04.<html>  
05.<head>  
06.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
07.<title>Login home page</title>  
08.</head>  
09.<body>  
10.<span color="red">Login successfully!</span>  
11.</body>  
12.</html>  

When we enter the following url in the browser address bar:

Ha ha, the built-in login page, very interesting. If you haven't used spring security, you probably haven't found out where I configure my username and password. Look at the following code. Here's the username and password:

<user name="sharp" password="sharp" authorities="ROLE_USER"/>  

Test one:

We enter user name: admin; password: admin, then click submit query, the final page is as follows:

Login failed!

Test 2: We enter user name: sharp; password: sharp; as follows:

After clicking submit query, the page is as follows:

The page jumps to the index.jsp page and the login is successful.

Haha, is it easy to log in with this?

(Blogger's Warm Tip: I started my test with myeclipse, all the operations were okay, and then changed to eclipse-Java EE. Every time tomcat was started, eclipse reported Server tomcat V6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try to increase the time out in the server editor error, tomcat was started 45 seconds later. Stop automatically. I checked the reasons in Baidu and found a solution. The solution is as follows:

[java] view plain copy 
01.Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.  
02.modify workspace\.metadata\.plugins\org.eclipse.wst.server.core\servers.xml Papers.  
03.<servers>  
04.<server hostname="localhost" id="JBoss v5.0 at localhost" name="JBoss v5.0 at  
05.localhost" runtime-id="JBoss v5.0" server-type="org.eclipse.jst.server.generic.jboss5"  
06.server-type-id="org.eclipse.jst.server.generic.jboss5" start-timeout="1000" stop-  
07.timeout="15" timestamp="0">  
08.<map jndiPort="1099" key="generic_server_instance_properties" port="8090"  
09.serverAddress="127.0.0.1" serverConfig="default"/>  
10.</server>  
11.</servers>  
12.hold start-timeout="45" Change to start-timeout="1000" Or longer  
13.restart eclipse That's all right.  
14.The reason for this is: start-up tomcat Time ratio required45The second is large. Eclipse Will judge tomcat Whether it is started at the default time, if it is by default45If you don't start in seconds, you will report a mistake.  

On the basis of the first example, I made a second one.

The second example:

The login page in the first example is the default page of spring security. This rigid page can not meet the ever-changing user needs. So I will customize the login interface in this example. Here we will add several jar packages. The directory under the latest lib package is as follows:

Create a new login.jsp page code as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
02.<%@ page language="java" contentType="text/html; charset=UTF-8"  
03.    pageEncoding="UTF-8"%>  
04.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
05.<html>  
06.<head>  
07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
08.<title>User login</title>  
09.</head>  
10.<body onLoad="document.f.j_username.focus();">  
11.<c:if test="${not empty param.login_error}">  
12.    <font color="red">  
13.        Logon failed, please try again.<br/><br/>  
14.        Reason:<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>  
15.    </font>  
16.</c:if>  
17.<form name="f" action="<c:url value='j_spring_security_check'/>" method="POST">  
18.    <table>  
19.        <tr>  
20.            <td>User name:</td>  
21.            <td>  
22.                <input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"&gt;&lt;c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/>  
23.            </td>  
24.        </tr>  
25.        <tr>  
26.            <td>dense     code:</td>  
27.            <td><input type='password' name='j_password'></td>  
28.        </tr>  
29.        <tr>  
30.            <td>  
31.                <input type="checkbox" name="_spring_security_remember_me"></td><td>Automatic login within two weeks  
32.            </td>  
33.        </tr>  
34.        <tr>  
35.            <td colspan='2' align="center">  
36.                <input name="submit" type="submit">    
37.                <input name="reset" type="reset">  
38.            </td>  
39.        </tr>  
40.    </table>  
41.</form>  
42.</body>  
43.</html>  

Modify the application Context-security.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>  
02.<beans:beans xmlns="http://www.springframework.org/schema/security"  
03.    xmlns:beans="http://www.springframework.org/schema/beans"  
04.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
05.    xsi:schemaLocation="http://www.springframework.org/schema/beans   
06.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
07.        http://www.springframework.org/schema/security  
08.        http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
09.    <!-- Automatic configuration mode, intercept all requests, there are ROLE_USER Only then can it pass through -->  
10.    <http auto-config="true">  
11.        <intercept-url pattern="/login.jsp*"  access="IS_AUTHENTICATED_ANONYMOUSLY" />  
12.        <intercept-url pattern="/**" access="ROLE_USER"/>  
13.        <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/>   
14.    </http>  
15.    <!-- Authentication Manager. User name and password are integrated in the configuration file -->   
16.    <authentication-manager>  
17.        <authentication-provider>  
18.            <user-service>  
19.                <user name="sharp" password="sharp" authorities="ROLE_USER"/>  
20.            </user-service>  
21.        </authentication-provider>  
22.    </authentication-manager>  
23.    <!-- Specify Chinese resources. The default namespace is security,So prefix it. beans: -->   
24.     <beans:bean id="messageSource"   
25.        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
26.        <beans:property name="basename"  value="classpath:org/springframework/security/messages_zh_CN"/>    
27.     </beans:bean>  
28.</beans:beans>  

We enter the following url in the browser address bar and click Enter. The interface is as follows:

Logon failed!

Test 2: We enter user name: sharp; password: sharp; as follows:

Click to submit the query and the results are as follows:

The third example:

As long as programmers who have been exposed to privilege management know, general privilege management has the concept of role, but traditional roles are modeled in the database, and then implemented by programming. In spring security, there is the concept of role, which is very convenient to use. In the example above, we used a role ROLE_USER. Now we add a role ROLE_ADMIN. We modify the application Context-security.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>  
02.<beans:beans xmlns="http://www.springframework.org/schema/security"  
03.    xmlns:beans="http://www.springframework.org/schema/beans"  
04.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
05.    xsi:schemaLocation="http://www.springframework.org/schema/beans   
06.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
07.        http://www.springframework.org/schema/security  
08.        http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
09.    <!-- Automatic configuration mode, intercept all requests, there are ROLE_USER Only then can it pass through -->  
10.    <http auto-config="true">  
11.        <intercept-url pattern="/login.jsp*"  access="IS_AUTHENTICATED_ANONYMOUSLY" />  
12.        <!-- increase ROLE_ADMIN role-->  
13.        <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN"/>  
14.        <intercept-url pattern="/**" access="ROLE_USER"/>  
15.        <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/>   
16.    </http>  
17.    <!-- Authentication Manager. User name and password are integrated in the configuration file -->   
18.    <authentication-manager>  
19.        <authentication-provider>  
20.            <user-service>  
21.                <!-- Add to ROLE_ADMIN role -->  
22.                <user name="admin" password="admin" authorities="ROLE_USER,ROLE_ADMIN"/>  
23.                <user name="sharp" password="sharp" authorities="ROLE_USER"/>  
24.            </user-service>  
25.        </authentication-provider>  
26.    </authentication-manager>  
27.    <!-- Specify Chinese resources. The default namespace is security,So prefix it. beans: -->   
28.     <beans:bean id="messageSource"   
29.        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
30.        <beans:property name="basename"  value="classpath:org/springframework/security/messages_zh_CN"/>    
31.     </beans:bean>  
32.</beans:beans>  

In addition, I created a new admin.jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"  
02.    pageEncoding="UTF-8"%>  
03.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
04.<html>  
05.<head>  
06.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
07.<title>Admin Management interface</title>  
08.</head>  
09.<body>  
10.<p style="color:red">admin.jsp page</p>  
11.</body>  
12.</html>  

Modify the index.jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"  
02.    pageEncoding="UTF-8"%>  
03.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
04.<html>  
05.<head>  
06.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
07.<title>Login home page</title>  
08.</head>  
09.<body>  
10.<span color="red">Login successfully!</span>  
11.<br/>  
12.<a href="admin.jsp">admin.jsp</a>  
13.</body>  
14.</html

Test one:

We entered the user name: sharp; password: sharp, the login was successful, we entered the page index.jsp:

Click the admin.jsp link and the results are as follows:

sharp users do not have permission for ROLE_ADMIN roles, so sharp cannot access admin.jsp pages.

Test two:

We entered the user name: admin; password: admin, the login was successful, we entered the page index. JSP (as shown above).

Then

Click the admin.jsp link and the results are as follows:

User admin can access admin.jsp pages.

Well, today's study is over!

Summary: Today are all specific operations, and these operations on the Internet are incredible, but I want to learn spring security must start from this step, now I do not have a deep understanding of spring security, the whole article is how to code, and without some knowledge of the explanation, I will try my best to step by step in-depth, do software is best to know why, tomorrow to see if it can be studied. The next article starts with the combination of spring security and database.

Posted by oc1000 on Sat, 06 Apr 2019 16:21:31 -0700