1. 程式人生 > >spring security 採用 資料庫配置檢測使用者登入,並跳轉不同頁面

spring security 採用 資料庫配置檢測使用者登入,並跳轉不同頁面

applicationContext-security.xml

<?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.1.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">
	<global-method-security pre-post-annotations="enabled" />
	
	<http pattern="/images/**" security="none" />
	<http pattern="/widgets/**" security="none" />
	<http pattern="/css/**" security="none" />
	<http pattern="/style/**" security="none" />
	<http pattern="**/*.js" security="none" />
	<http pattern="**/*.swf" security="none" />
	<http pattern="/login.jsp" security="none" />
	<http pattern="/session-timeout.jsp" security="none"/>
	<http pattern="/session-expired.jsp" security="none"/>
	<http auto-config="true" use-expressions="true">		
		<!-- <intercept-url pattern="/**" access="isAuthenticated()" /> -->
		<intercept-url pattern="/**" access="permitAll" />
		<form-login login-page='/login.jsp' 
			 authentication-success-handler-ref="authSuccessHandlerImpl"
			 authentication-failure-handler-ref="authFailureHandlerImpl"/>
        
		<session-management invalid-session-url="/session-timeout.jsp">
            <concurrency-control max-sessions="1" expired-url="/session-expired.jsp"/>
        </session-management>
        	
		<logout logout-success-url="/login.jsp" delete-cookies="JSESSIONID"/>
	</http>
	
	<authentication-manager>
       <authentication-provider ref="daoAuthenticationProvider" />
    </authentication-manager>
	
	<beans:bean id="daoAuthenticationProvider"  class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
		<beans:property name="passwordEncoder" ref="passwordEncoder" />
		<beans:property name="userDetailsService" ref="userService" />
	</beans:bean>

	<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
	
	<beans:bean id="authSuccessHandlerImpl" class="com.wonders.stpt.security.service.AuthenticationSuccessHandlerImpl">
    </beans:bean>
    
    <beans:bean id="authFailureHandlerImpl" class="com.wonders.stpt.security.service.AuthenticationFailureHandlerImpl">
    </beans:bean>
</beans:beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>STPT_QUERY</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:/applicationContext.xml</param-value>
	</context-param>
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
	</listener>
	<!-- <listener>
		<listener-class>com.wonders.stpt.framework.web.listener.MyBatisInitListener</listener-class>
	</listener> -->
	
	<session-config>
		<session-timeout>120</session-timeout>
	</session-config>
	<welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
	<taglib>
		<taglib-uri>/struts-tags</taglib-uri>
		<taglib-location>/WEB-INF/tlds/struts-tags.tld</taglib-location>
	</taglib>
</web-app>


登陸失敗 AuthenticationFailureHandlerImpl

package com.wonders.stpt.security.service;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class AuthenticationFailureHandlerImpl
  implements AuthenticationFailureHandler
{
  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
    throws IOException, ServletException
  {
    response.sendRedirect(request.getContextPath() + "/login.jsp?login_error=1");
  }
}


登陸成功:AuthenticationSuccessHandlerImpl

package com.wonders.stpt.security.service;

import com.wonders.stpt.security.domain.SecurityLog;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class AuthenticationSuccessHandlerImpl
  implements AuthenticationSuccessHandler
{

  @Resource
  private SecurtiyLogService securityLogService;

  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
    throws IOException, ServletException
  {
    SecurityLog log = new SecurityLog(request.getRemoteAddr(), "登入", 
      authentication.getName());

    this.securityLogService.save(log);
    response.sendRedirect(request.getContextPath() + "/query.jsp");
  }

  public SecurtiyLogService getSecurityLogService() {
    return this.securityLogService;
  }

  public void setSecurityLogService(SecurtiyLogService securityLogService) {
    this.securityLogService = securityLogService;
  }

  public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }
}

user類 需要重寫 equals方法
package com.wonders.stpt.security.domain;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@Table(name="SEC_USER", uniqueConstraints={@javax.persistence.UniqueConstraint(columnNames={"USER_NAME"})})
public class User
  implements UserDetails
{
  private static final long serialVersionUID = -6642778955506920404L;
  private String id;
  private String username;
  private String realName;
  private String password;
  private String address;
  private String phoneNumber;
  private Boolean enabled;

  @Id
  @GeneratedValue(generator="generator")
  @GenericGenerator(name="generator", strategy="guid")
  @Column(name="ID", unique=true, nullable=false, length=32)
  public String getId()
  {
    return this.id;
  }

  public void setId(String id) {
    this.id = id;
  }

  @Column(name="USER_NAME", unique=true, nullable=false, length=50)
  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }
  @Column(name="REAL_NAME", length=100)
  public String getRealName() {
    return this.realName;
  }

  public void setRealName(String realName) {
    this.realName = realName;
  }
  @Column(name="PASSWORD", nullable=false)
  public String getPassword() {
    return this.password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
  @Column(name="PHONE_NUMBER", length=20)
  public String getPhoneNumber() {
    return this.phoneNumber;
  }

  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  @Column(name="IS_ENABLED", precision=1, scale=0)
  public boolean isEnabled() {
    return this.enabled.booleanValue();
  }

  public void setEnabled(Boolean enabled) {
    this.enabled = enabled;
  }
  @Column(name="ADDRESS", length=200)
  public String getAddress() {
    return this.address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Transient
  public Collection<GrantedAuthority> getAuthorities() {
    Set authoritys = new HashSet(0);

    return authoritys;
  }

  @Transient
  public boolean isAccountNonExpired() {
    return true;
  }

  @Transient
  public boolean isAccountNonLocked() {
    return true;
  }

  @Transient
  public boolean isCredentialsNonExpired() {
    return true;
  }

  public boolean equals(Object obj)
  {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    User other = (User)obj;
    if (this.id == null) {
      if (other.id != null)
        return false;
    } else if (!this.id.equals(other.id))
      return false;
    return true;
  }
}

user 檢測類 實現指定介面,達到通過資料庫檢測目的:
package com.wonders.stpt.security.service;

import com.wonders.stpt.framework.persist.HibernateDao;
import com.wonders.stpt.framework.service.AbstractBaseService;
import com.wonders.stpt.security.domain.User;
import com.wonders.stpt.security.persist.UserDao;
import com.wonders.stpt.security.utils.SecurityUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService extends AbstractBaseService<User, String>
  implements UserDetailsService
{
  private UserDao userDao;

  protected HibernateDao<User, String> getDao()
  {
    return this.userDao;
  }

  public void delete(String id)
  {
    this.userDao.delete(id);
  }

  @Transactional(readOnly=true)
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException
  {
    User user = this.userDao.loadUserByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("使用者:" + username + "沒有找到!");
    }
    return user;
  }
  @Autowired
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }
  @Transactional
  public void changePassword(User user, String password) {
    user.setPassword(DigestUtils.md5Hex(password));
    this.userDao.save(user);
  }

  public void save(User user)
  {
    if (user.getPassword().equals(SecurityUtils.getCurrentUserPassword()))
      getDao().save(user);
    else
      changePassword(user, user.getPassword());
  }
}


相關推薦

spring security 採用 資料庫配置檢測使用者登入不同頁面

applicationContext-security.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schem

django寫使用者登入判定制定頁面

1.首先看要設定登陸的介面 book/view.py @user_util.my_login #相當於 select_all=my_login(select_all) def select_all(request): # 查詢所有的書 book_list = Boo

spring security實現登入驗證以及根據使用者身份不同頁面

想關依賴,採用session加redis儲存使用者資訊 <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security

spring boot security 實現根據情況不同頁面功能

invalid static request config 隱藏 ctu gif cte send 在配置主類添加代碼 @Override protected void configure(HttpSecurity http) throws Except

Spring 筆記 -07- 使用 jQuery Ajax 非同步登入驗證使用者輸入資訊(maven)

Spring 筆記 -07- 使用 jQuery Ajax 非同步登入,並驗證使用者輸入資訊(maven) 本篇是對上一篇的專案的另一種實現加完善,上一篇 Spring 筆記 -06- 從 MySQL 建庫到 登入驗證資料庫資訊(maven) 本篇內容: (1)上一篇是使用同步的

Apache(httpd)配置--用戶認證域名和訪問日誌配置

用戶認證 域名跳轉 訪問日誌 一、用戶認證 用戶認證功能就是在用戶訪問網站的時候,需要輸入用戶名密碼才能進行訪問。一些比較好總要的站點和網站後臺都會加上用戶認證,以保證安全。實例:下面對zlinux.com站點來做一個全站的用戶認證: 步驟1:編輯虛擬主機配置文件 [root@zlinux ~]#

thinkphp5登入儲存session、根據不同使用者許可權不同頁面

本文介紹如何在thinkphp5中完成登入並儲存session、然後根據不同的使用者許可權跳轉相應頁面功能的實現。完成該步驟主要有以下三個步驟完成。 一、密碼校驗 這裡view層提交過來的使用者名稱和密碼是不加密的,資料中的密碼是經過md5加密的,所以首

登入不同許可權不同頁面

action 登入時查詢使用者許可權,講許可權資訊以集合形式存放在使用者的實體類中!    <pre name="code" class="java"> ActionCo

判斷session失效登入頁面

一,首先在登入頁面加入以下程式碼,作用是使用ifrme等載入頁面時,跳轉登入頁面會巢狀在框架內,讓登入頁面全屏<script language="JavaScript"> if (window != top) { top.locat

web 開發,個人中心每個請求判斷使用者是否登入若沒有登入登入頁面登入成功後返回之前頁面

首先要在web.xml裡面配製一個usercenter過濾器,當用戶請求中包含http.../usercenter/..如下時,則會執行userCenterFilter過濾器,判斷使用者是否登入,若沒有登入,則通過req.getRequestURI();獲得請求路徑,通過r

spring security起步三:自定義登入配置與form-login屬性詳解

在上一篇部落格spring security起步二:自定義登入頁中我們實現瞭如何自定義登入頁,但是還存在很多問題: 1.spring security如何對登入請求進行攔截 2.登入成功後如何跳轉 3.登入失敗後如何跳轉 form-login屬性詳解

idea+maven + spring security +springmvc入門 (自定義登入頁面附idea如何建立web專案

第一次使用idea,上午在eclipse中 學習了spring security 入門,下午試試在idea中搭建。 剛開始 我以為 直接將eclipse的 檔案 copy過來就行了,結果發現copy過來以後 各種報錯。 後來把m

Spring Security教程(四):自定義登入

在前面的例子中,登陸頁面都是用的Spring Security自己提供的,這明顯不符合實際開發場景,同時也沒有退出和登出按鈕,因此在每次測試的時候都要通過關閉瀏覽器來登出達到清除session的效果。 一、自定義頁面 login.jsp: <%@ page language="

Spring Security之旅————————————restful風格介面簡述過濾器配置(2)

restful介面的完成度簡介 , 分為四級 利用三種方式攔截介面請求  Filter package com.sola.filter; import java.io.IOException; import javax.servlet.Filter; im

spring-security-oauth2(二) 自定義個性化登入

自定義認證邏輯 1.認證邏輯介面 spring-security使用者登入邏輯驗證介面org.springframework.security.core.userdetails.UserDetailsService只有一個方法 UserDetails loadUserByUsername

Spring-Security整合CAS之Spring-Security.xml部分配置詳解

<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://w

Spring Security 實現 antMatchers 配置路徑的動態獲取

1. 為什麼要實現動態的獲取 antMatchers 配置的資料           這兩天由於公司專案的需求,對 spring security 的應用過程中需要實現動態的獲取 antMatch

spring boot 多資料庫配置問題

application.yml配置: spring:   jpa:     show-sql: true   application:     name: xxx   thymeleaf:     cache: false #thymeleaf     mode: LEGA

Spring Security會話控制(單使用者登入

在專案開發過程中很難避免說單使用者登入系統,或者說對登入會話進行限制,例如說,只能兩臺機器登入使用者 那麼話不多說,直接看配置程式碼: XML配置 如果你想限制單個使用者訪問你的應用程式的能力。Spring Security通過後面簡單的配置馬

Spring Security實現使用者名稱或者手機號登入

使用Spring Security來管理web專案的使用者許可權,是很多Java管理系統經常使用的方法。 然而,當前很多網站都支援使用手機號+密碼登入網站。畢竟,使用者名稱這個東西肯定沒有自己的手機號好記。 Spring Security許可權管理 Spr