1、實現功能html
2、數據表設計java
爲了測試方便,這裏建立一個簡單的數據表,只含有name和password兩個字段。至於角色,權限等,這裏都先不考慮。web
插入一條數據,name爲admin,password爲e10adc3949ba59abbe56e057f20f883e(這是123456經md5加密後獲得的值)。spring
3、配置文件緩存
1 在pom.xml中添加三個相關的包cookie
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-core</artifactId>
- <version>${org.springframework.security.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-config</artifactId>
- <version>${org.springframework.security.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-web</artifactId>
- <version>${org.springframework.security.version}</version>
- </dependency>
2 web.xml中添加過濾器session
- <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>/service/*</url-pattern>
- </filter-mapping>
3 src/main/resource/spring/applicationContext-security.xml的內容爲mybatis
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://www.springframework.org/schema/security"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-3.1.xsd">
-
-
- <http access-denied-page="/service/login/unSecurity" entry-point-ref="authenticationProcessingFilterEntryPoint">
-
- <intercept-url pattern="/service/index/index" access="ROLE_AUTHORITY"/>
-
-
- <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" />
- <logout logout-url="/service/login/logout" logout-success-url="/" invalidate-session="true"
- delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"/>
- <session-management invalid-session-url="/service/login/unSecurity" session-authentication-strategy-ref="sas"/>
- </http>
-
-
- <beans:bean id="loginFilter" class="com.zheng.shared.security.JadeUserPwdAuthFilter">
-
- <beans:property name="filterProcessesUrl" value="/service/login/userLogin"/>
-
- <beans:property name="authenticationManager" ref="myAuthenticationManager"/>
-
- <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"/>
-
- <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"/>
-
-
- <beans:property name="sessionAuthenticationStrategy" ref="sas"/>
- </beans:bean>
- <beans:bean id="loginLogAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
- <beans:property name="alwaysUseDefaultTargetUrl" value="true"/>
- <beans:property name="defaultTargetUrl" value="/service/login/loginSucc"/>
- </beans:bean>
- <beans:bean id="simpleUrlAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
-
- <beans:property name="defaultFailureUrl" value="/service/login/loginFail"/>
- </beans:bean>
- <beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
- <beans:property name="maximumSessions" value="1"/>
- <beans:property name="exceptionIfMaximumExceeded" value="false"/>
- <beans:constructor-arg name="sessionRegistry" ref="sessionRegistry"/>
- </beans:bean>
- <beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
- <authentication-manager alias="myAuthenticationManager">
- <authentication-provider ref="authenticationProvider"/>
- </authentication-manager>
- <beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
-
- <beans:property name="hideUserNotFoundExceptions" value="false" />
-
- <beans:property name="userDetailsService" ref="userDetailService" />
-
-
-
- <!-- <beans:property name="passwordEncoder" ref="passwordEncode"/>
- <beans:property name="saltSource" ref="saltSource" /> -->
- </beans:bean>
-
- <beans:bean id="passwordEncode" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
- <beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
- <beans:property name="userPropertyToUse" value="id"/>
- </beans:bean>
- <beans:bean id="userDetailService" class="com.zheng.service.impl.UserServiceImpl" />
-
- <beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
- <beans:property name="loginFormUrl" value="/service/login/unSecurity" />
- </beans:bean>
-
- </beans:beans>
4、相關代碼app
1src/main/Java/com/zheng/shared/sercurity/JadeUserPwdAuthFilter.java中的代碼爲ide
- package com.zheng.shared.security;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.authentication.AuthenticationServiceException;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-
- import com.zheng.bean.User;
- import com.zheng.dao.UserMapper;
-
- public class JadeUserPwdAuthFilter extends UsernamePasswordAuthenticationFilter {
-
-
- public static final String USERNAME = "userName";
- public static final String PASSWORD = "userPassword";
-
- @Autowired
- private UserMapper userDao;
-
- @Override
- public Authentication attemptAuthentication(HttpServletRequest request,
- HttpServletResponse response) throws AuthenticationException {
- if (!request.getMethod().equals("POST")) {
- throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
- }
-
- String userName = request.getParameter(USERNAME);
- String password = request.getParameter(PASSWORD);
-
- User user = userDao.findUserByUserName(userName);
- System.out.println("username: " + user.getUsername());
- System.out.println("password: " + user.getPassword());
-
-
- UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
-
- setDetails(request, authRequest);
-
- return this.getAuthenticationManager().authenticate(authRequest);
- }
- }
2 src/main/java/com/zheng/service/UserService.java的內容爲
- package com.zheng.service;
-
- import org.springframework.security.core.userdetails.UserDetailsService;
-
- public interface UserService extends UserDetailsService{
-
- }
3 src/main/java/com/zheng/service/impl/UserServiceImpl.java的內容爲
- package com.zheng.service.impl;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
-
- import com.zheng.bean.User;
- import com.zheng.dao.UserMapper;
- import com.zheng.service.UserService;
-
-
- public class UserServiceImpl implements UserService{
-
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- User user = null;
- try {
- user = userMapper.findUserByUserName(username);
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (user == null) {
- throw new UsernameNotFoundException("用戶名或密碼不正確!");
- }
- System.out.println("username: " + user.getUsername());
- System.out.println("password: " + user.getPassword());
-
- return user;
- }
-
- }
4 src/main/java/com/zheng/bean/User.java的內容爲
- package com.zheng.bean;
-
- import java.io.Serializable;
- import java.util.Collection;
-
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
-
- public class User implements UserDetails , Serializable {
- private static final long serialVersionUID = 123L;
-
- private String userName;
-
- private String password;
-
- private Collection<GrantedAuthority> authorities;
-
- @Override
- public String getUsername() {
- return this.userName;
- }
-
- @Override
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @Override
- public Collection<? extends GrantedAuthority> getAuthorities() {
- return authorities;
- }
-
- public void setAuthorities(Collection<GrantedAuthority> authorities) {
- this.authorities = authorities;
- }
-
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
-
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
-
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
-
- @Override
- public boolean isEnabled() {
- return true;
- }
- }
特別須要注意的是:用戶只有在不過時、沒被鎖定、沒被禁用的狀況下才能登陸成功,因此isEnabled()方法的返回值設爲真,表示用戶沒有禁用。
5 src/main/java/com/zheng/dao/UserMapper.java的內容爲
- package com.zheng.dao;
-
- import com.zheng.bean.User;
-
- public interface UserMapper {
-
- User findUserByUserName(String name);
- }
6 src/main/resources/config/mybatis/mapper/UserMapper.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.zheng.dao.UserMapper" >
- <resultMap id="BaseResultMap" type="com.zheng.bean.User" >
- <result column="name" property="userName" jdbcType="VARCHAR" />
- <result column="password" property="password" jdbcType="VARCHAR" />
- </resultMap>
-
- <select id="findUserByUserName" parameterType="string" resultMap="BaseResultMap" >
- select * from user where name = #{userName}
- </select>
-
- </mapper>
7 LoginController.java中響應登陸成功和失敗的方法爲
- @RequestMapping("/loginSucc")
- @ResponseBody
- public Map<String,Object> loginSucc(HttpServletRequest request){
- System.out.println("登陸成功!");
- Map<String,Object> result = new HashMap<String,Object>();
- return result;
- }
-
- @RequestMapping("/loginFail")
- @ResponseBody
- public Map<String,Object> loginFail(HttpServletRequest request){
- System.out.println("登陸失敗!");
- Map<String,Object> result = new HashMap<String,Object>();
- return result;
- }
5、運行結果