[Spring ---- Security] four, custom page

In the previous example, the landing pages are used Spring Security to provide their own, this is obviously not realistic development scenarios, but there is no exit and logout button, so when each test must be written off by closing the browser to achieve clear session results.

A custom page

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>自定义登陆页面</title>
    </head>
    <body>
        <div class="error ${param.error == true ? '' : 'hide'}">  
                登陆失败<br>  
            ${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message}  
        </div>  
        <form method="post" action="${pageContext.request.contextPath}/j_spring_security_check" style="width:260px; text-align: center">  
            <fieldset>  
                <legend>登陆</legend>  
                用户: <input type="text" name="j_username" style="width: 150px;" value="${sessionScope['SPRING_SECURITY_LAST_USERNAME']}" />
                <br/>  
                密码: <input type="password" name="j_password" style="width: 150px;" />
                <br/>  
                <input type="checkbox" name="_spring_security_remember_me" />记住我<br/>  
                <input type="submit" value="登陆" />
                <input type="reset" value="重置" />
            </fieldset>  
       </form>  
    </body>
</html>

Description:

  • Of particular note is a form of action that address form to submit login information, which is defined internal security, while a custom form , the form of action should be set to / j_spring_security_check . Note that using the absolute path to avoid problems landing page stored in the page may bring.
  • j_username , enter the login name of the parameter name, j_password parameter name, password, and under normal circumstances, these two will not be modified.

  • _spring_security_remember_me , choose whether to allow automatic login name parameter. This parameter can be directly set a the CheckBox , without setting value , the Spring Security will judge for themselves whether it is selected, this is the internal security provided, only need to configure, you do not need to achieve.

 

Second, the development of the configuration page

Configuration files are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security.xsd">
    <!-- 
    1.http部分配置如何拦截用户请求。auto-config='true'将自动配置几种常用的权限控制机制,包括form, anonymous, rememberMe。
    2.利用intercept-url来判断用户需要具有何种权限才能访问对应的url资源,可以在pattern中指定一个特定的url资源,也可以使用通配符指定一组
    类似的url资源。例子中定义的两个intercepter-url,第一个用来控制对/admin.jsp的访问,第二个使用了通配符/**,说明它将控制对系统中所有
    url资源的访问。
    3.在实际使用中,Spring Security采用的是一种就近原则,就是说当用户访问的url资源满足多个intercepter-url时,系统将使用第一个符合
    条件的intercept-url进行权限控制。在我们这个例子中就是,当用户访问/admin.jsp时,虽然两个intercept-url都满足要求,但因为第一个
    intercept-url排在上面,所以Spring Security会使用第一个intercept-url中的配置处理对/adminPage.jsp的请求,也就是说
    只有那些拥有了ROLE_ADMIN权限的用户才能访问/admin.jsp。
    4.access指定的权限都是以ROLE_开头的,实际上这与Spring Security中的Voter机制有着千丝万缕的联系,只有包含了特定前缀的字符串才会
    被Spring Security处理。
     -->
    <http auto-config='true'>
        <!-- IS_AUTHENTICATED_ANONYMOUSLY表示允许匿名访问 -->
        <intercept-url pattern="/page/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <!-- ROLE_ADMIN角色允许访问 -->
        <intercept-url pattern="/page/admin.jsp" access="ROLE_ADMIN" />
        <!-- ROLE_USER角色允许访问任何页面,但不包括上面配置的页面,因为SpringSecurity采用就近原则 -->
        <intercept-url pattern="/**" access="ROLE_USER" />
        <!-- 登录页面配置,default-target-url登录成功页面,authentication-failure-url失败页面 -->
        <form-login login-page="/page/login.jsp" default-target-url="/user.jsp" authentication-failure-url="/page/login.jsp?error=true"/>
        <!-- 注销配置,invalidate-session是否清除缓存,logout-success-url注销后跳转页面,logout-url提交地址 -->  
        <logout invalidate-session="true" logout-success-url="/page/login.jsp" logout-url="/j_spring_security_logout"/>    
    </http>
    
    <!-- 默认数据库对用户进行存储 -->
    <authentication-manager>
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="select username,password,status as enabled from user where username = ?"
                authorities-by-username-query="select user.username,role.name from user,role,user_role 
                                       where user.id=user_role.user_id and 
                                       user_role.role_id=role.id and user.username=?"/>
           </authentication-provider>
    </authentication-manager>
</beans:beans>

 

Description:

  • form-login This label is to configure the landing page, which attribute login-page is to configure the login page, default-target-url configuration after a successful jump to the landing page, authentication-failure-url Jump after configure the authentication fails page.
  • In the above configuration, the landing page is certainly not intercept anyone should have access to, <intercept-url pattern = " / page / login.jsp" access = "IS_AUTHENTICATED_ANONYMOUSLY" /> configuration means that allow anonymous user access is no identity can access; there is another configuration: <HTTP pattern = "/ Page / the login.jsp" Security = "none"> </ HTTP> , this configuration to achieve the goal is the same.
  • logout This tab is used to configure quit or cancellation, in which the properties of the invalidate-the session , configure whether to remove the session, logout-url-Success configured cancellation after a successful jump page, logout-url submit to exit or cancellation of address, so we in the configuration quit or log off time, just to set url / j_spring_security_logout can be, this is the address of the internal security achieved.
  • form-login tab and a particular attention to the property use-Expressions , if set to true , the corresponding login page intercept-url configuration of access to do the appropriate changes, otherwise the project will start when an error with the following error:

If use-expressns = "true" , it represents instead SpEL expression. SpEL allows the use of specific access control rules expression language. And a simple string such as different ROLE_USER, the configuration file can be specified trigger expression language method call, reference system property, the value of the computer and so on. http tab arranged to read as follows:

  <http auto-config="false" use-expressions="true">  
        <intercept-url pattern="/page/login.jsp" access="permitAll" />  
        <intercept-url pattern="/page/user.jsp" access="hasRole('ROLE_ADMIN')" />  
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />  
        <form-login login-page="/page/login.jsp" default-target-url="/page/user.jsp" authentication-failure-url="/login.jsp?error=true" />  
        <logout invalidate-session="true" logout-success-url="/page/login.jsp" logout-url="/j_spring_security_logout"/>    
    </http>  

Other configurations in the configuration file has a detailed explanation in front of several blog, not go into here.

Third, other documents

user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <h1>User Page</h1>
        <a href="${pageContext.request.contextPath}/j_spring_security_logout">退出登陆</a>  
    </body>
</html>

 

admin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <h1>Admin Page</h1>
        <a href="${pageContext.request.contextPath}/j_spring_security_logout">退出登陆</a>
    </body>
</html>

 

This defines two pages, user.jsp users and administrators can access, admin.jsp only administrators can access while two pages are written off Address button, logout button to submit the above is the configuration file address / j_spring_security_logout.

Like the previous chapters pom.xml

 

Under the default page modify web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>SpringSecurity</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-*.xml</param-value>
    </context-param>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>/page/login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

Fourth, the results

 

 

 When you enter the general user's user name and password, and check two weeks without landing, because admin.jsp page to have administrator privileges to access, so ordinary users access failed, user.jsp page can be accessed; then close the page after , access to resources once again, because two weeks without logging in check, so you can successfully access; but when click Log, is once again visit will jump to the landing page, requires login to access.

 

When you enter the administrator name and password, and check two weeks without logging, validation is successful, jump to user.jsp, while adminPage.jsp can also visit, this time to close a page and re-access resources, because check 2 weeks without logging in, so you can successfully access; and then log off, which is longer have access to resources, it will jump to the landing page, requires login to access.

 

 

Guess you like

Origin blog.csdn.net/ningjiebing/article/details/89411058