需要用到的技术:
- Spring 3.2.8.RELEASE
- Spring Security 3.2.3.RELEASE
- Eclipse 4.2
- JDK 1.6
- Maven 3
- Tomcat 7 (Servlet 3.x)
在这个例子中,上一个Spring Security hello world声明示例 将被重用,增强这个以支持自定义登录表单。
2. 工程目录结构
3. Spring Security配置
Spring Security通过注解配置,如下图所示:
package com.yiibai.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("yiibai").password("123456").roles("USER"); } //.csrf() is optional, enabled by default, if using WebSecurityConfigurerAdapter constructor @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").access("hasRole('ROLE_USER')") .and() .formLogin().loginPage("/login").failureUrl("/login?error") .usernameParameter("username").passwordParameter("password") .and() .logout().logoutSuccessUrl("/login?logout") .and() .csrf(); } }
<http auto-config="true"> <intercept-url pattern="/admin**" access="ROLE_USER" /> <form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password" /> <logout logout-success-url="/login?logout" /> <!-- enable csrf protection --> <csrf/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="yiibai" password="123456" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager>
4. 自定义登录表单
4.1 这个页面用于显示自定义登录表单。如果CSRF保护被启用,记得要在登录和注销表单中添加${_csrf.token}。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Login Page</title> <style> .error { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .msg { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } #login-box { width: 300px; padding: 20px; margin: 100px auto; background: #fff; -webkit-border-radius: 2px; -moz-border-radius: 2px; border: 1px solid #000; } </style> </head> <body onload='document.loginForm.username.focus();'> <h1>Spring Security Custom Login Form (Annotation)</h1> <div id="login-box"> <h2>Login with Username and Password</h2> <c:if test="${not empty error}"> <div class="error">${error}</div> </c:if> <c:if test="${not empty msg}"> <div class="msg">${msg}</div> </c:if> <form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'> <table> <tr> <td>User:</td> <td><input type='text' name='user' value=''></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='pass' /></td> </tr> <tr> <td colspan='2'> <input name="submit" type="submit" value="submit" /> </td> </tr> </table> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> </div> </body> </html>
4.2 这个页面用来显示欢迎信息,这是一个默认页面。
<%@page session="false"%> <html> <body> <h1>Title : ${title}</h1> <h1>Message : ${message}</h1> </body> </html>
4.3 这页面有密码保护,只有经过验证的用户才允许访问。
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@page session="true"%> <html> <body> <h1>Title : ${title}</h1> <h1>Message : ${message}</h1> <c:url value="/j_spring_security_logout" var="logoutUrl" /> <!-- csrt support --> <form action="${logoutUrl}" method="post" id="logoutForm"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> <script> function formSubmit() { document.getElementById("logoutForm").submit(); } </script> <c:if test="${pageContext.request.userPrincipal.name != null}"> <h2> Welcome : ${pageContext.request.userPrincipal.name} | <a href="javascript:formSubmit()"> Logout</a> </h2> </c:if> </body> </html>
5. Spring MVC控制器
一个简单的控制器,如下所示:
package com.yiibai.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET) public ModelAndView welcomePage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Custom Login Form"); model.addObject("message", "This is welcome page!"); model.setViewName("hello"); return model; } @RequestMapping(value = "/admin**", method = RequestMethod.GET) public ModelAndView adminPage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Custom Login Form"); model.addObject("message", "This is protected page!"); model.setViewName("admin"); return model; } //Spring Security see this : @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login( @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("msg", "You've been logged out successfully."); } model.setViewName("login"); return model; } }
6. 初始化类
6.1 初始化类启用Spring Security配置。
package com.yiibai.config.core; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
6.2 初始化类启用Spring MVC。
package com.yiibai.config.core; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.yiibai.config.AppConfig; public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { AppConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
package com.yiibai.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.yiibai.web.*" }) @Import({ SecurityConfig.class }) public class AppConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
7. 示例
7.1. 打开欢迎页面 – http://localhost:8080/spsecurity-custom-login-form-annotation/welcome
7.2 尝试访问 http://localhost:8080/spsecurity-custom-login-form-annotation/admin 页面,它将会显示自定义登录表单。如下图中所示:
7.3. 如果用户名和密码不正确,将显示页面: http://localhost:8080/spsecurity-custom-login-form-annotation/login?error
7.4. 如果用户名和密码都正确,Spring将请求重定向到原来请求的URL并显示该网页内容。
7.5. 尝试注销,它会重定向到 http://localhost:8080/spsecurity-custom-login-form-annotation/login?logout 页面,如下所示:
下载源代码
参考