Spring Security入門Demo

21685 ワード

一、Spring Security概要
SpringSecurity、Spring AOPとサーブレットフィルタに基づくセキュリティフレームワークです.Webリクエスト・レベルとメソッド・コール・レベルでアイデンティティの確認と認可を処理しながら、包括的なセキュリティ・ソリューションを提供します.Spring Frameworkに基づいてSpring Securityは依存注入(DI,Dependency Injection)と面切り技術を十分に利用している.
 
二、建設工事
リファレンスhttp://blog.csdn.net/haishu_zheng/article/details/51490299を使用して、spring-security-demoというMavenプロジェクトを2つ目の方法で作成します.
プロジェクトの最終ディレクトリ構造は
Spring Security入门Demo_第1张图片
 
三、ソースコード
1 pom.xmlに必要なパッケージを導入

  4.0.0
  spring-security-demo
  spring-security-demo
  0.0.1-SNAPSHOT
  war
  spring-security-demo
  
  
    UTF-8
  
    
        
            javax
            javaee-api
            7.0
            provided
        
    
        jstl
        jstl
        1.2
    
        
            org.springframework
            spring-webmvc
            3.2.9.RELEASE
            jar
            compile
        
        
            org.springframework
            spring-context
            3.2.9.RELEASE
        
        
            org.springframework.security
            spring-security-config
            3.1.6.RELEASE
            jar
            compile
        
        
            org.springframework.security
            spring-security-taglibs
            3.1.6.RELEASE
            jar
            compile
        
        
            log4j
            log4j
            1.2.15
            jar
            compile
        
    
 

2 web.xml


  spring-security-demo
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	
	
		springSecurityFilterChain
		/*
	

	
		contextConfigLocation
		
		/WEB-INF/spring-security.xml
		/WEB-INF/applicationContext.xml
		
	

	
		spring
		org.springframework.web.servlet.DispatcherServlet
		1
	
	
		spring
		/
	

	
		org.springframework.web.context.ContextLoaderListener
	

ここでspringsecurityに関する2つの構成は、プロジェクト内のすべてのパスのリソースがSpring Securityを通過することを示します.
注意:DelegatingFilterProxyをDispatcherServiceletの前に書いたほうがいいです.そうしないとSpring Securityは正常に動作しない可能性があります.
 
3 spring-servlet.xml



	
	

このXML構成はビュー解析器を宣言する.コントローラでは、JSP名に従って/WEB-INF/jspの対応する位置にマッピングされます.
4 applicationContext.xml



	
	

	
	

	
	


5 spring-security.xml


	
	
	
	
		
		
		
		
		
		
			
		
	
	
	
	
	
	        
	        		
	        
	
	
	
	

	
	
	

分析:
(一)
ここで/auth/loginの権限はpermitAllであり、すべての人がこのページにアクセスできることを示しています./main/adminの権限はROLE_ADMINは、ROLE_に属することを示すADMINロールのユーザーのみがこのページにアクセスできます./main/commonの権限はROLE_USER,表示属于ROLE_USERのユーザーのみがこのページにアクセスできます.
 
SpringEL式を使用してキャラクタのアクセスを指定することに注意してください.
式の使用方法は次のとおりです.
hasRole([role])は、現在のマスターが特定のロールを持っている場合にtrueを返します.
hasAnyRole([role 1,role 2])は、現在のマスターが提供されているロール(カンマで区切られた文字列キュー)を持っている場合にtrueを返します.
principalでは、現在のユーザーを表すマスターオブジェクトに直接アクセスできます.
authenticationでは、現在のAuthenticationオブジェクトに直接アクセスしてSecurityContextから取得できます.
permitAllはtrueを返します
denyAllはfalseに戻った
isAnonymous()ユーザーが匿名でログインしているユーザーであればtrueを返します.
isRememberMe()ユーザーがremember-meでログインしているユーザーであればtrueを返します.
isAuthenticated()ユーザーが匿名でない場合はtrueを返します
isFullyAuthenticated()ユーザーが匿名でもremember-meでもログインしていないユーザーである場合、trueが返されます.
 
(二)
        
は、/auth/loginというマッピングによるログインを示す. 
検証に失敗した場合、URL:/auth/loginを返します.error=trueログインに成功した場合、デフォルトは:/main/common
 
(三)
ここではsession失効機能をオンにしました.ログアウトURL:/auth/logout;ログアウトに成功したら、/auth/loginに移行します.
 
(四)
    

カスタムのCustomUserDetailsServiceは、SpringSecurityを実装するUserDetailsServiceインタフェースですが、データベース操作を行っても書き換えました.
 
6 loginpage.jsp









Insert title here



	

Login

${error}


7 commonpage.jsp





Insert title here


	

Common Page

.

Go AdminPage
ログインを

8 adminpage.jsp





Insert title here


	

Admin Page

ログインを

9 deniedpage.jsp





Insert title here


	

!

Admin !

ログインを

10データモデルDbUser.java
package com.demo.domain;

public class DbUser {

	private String username;
	private String password;
	private Integer access;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAccess() {
		return access;
	}

	public void setAccess(Integer access) {
		this.access = access;
	}

}

11 UserDao.JAvaは、初期化されたListによってデータベース操作をシミュレートする
package com.demo.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import com.demo.domain.DbUser;

public class UserDao {

	protected static Logger logger = Logger.getLogger("dao");

	public DbUser getDatabase(String username) {

		List users = internalDatabase();

		for (DbUser dbUser : users) {
			if (dbUser.getUsername().equals(username) == true) {
				logger.debug("User found");
				return dbUser;
			}
		}
		logger.error("User does not exist!");
		throw new RuntimeException("User does not exist!");

	}

	/**
	 *      
	 */
	private List internalDatabase() {

		List users = new ArrayList();
		DbUser user = null;

		user = new DbUser();
		user.setUsername("admin");

		// "admin"  MD5   
		user.setPassword("21232f297a57a5a743894a0e4a801fc3");
		user.setAccess(1);

		users.add(user);

		user = new DbUser();
		user.setUsername("user");

		// "user"  MD5   
		user.setPassword("ee11cbb19052e40b07aac0ca060c23ee");
		user.setAccess(2);

		users.add(user);

		return users;

	}
}

12 CustomUserDetailsService.JAva,カスタムUserDetailsService,UserDetailsServiceを継承することで柔軟なカスタムUserDetailsServiceを実現
package com.demo.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import com.demo.dao.UserDao;
import com.demo.domain.DbUser;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *       service          .                .       UserDetailsService
 * 
 */
public class CustomUserDetailsService implements UserDetailsService {

	protected static Logger logger = Logger.getLogger("service");

	private UserDao userDAO = new UserDao();

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserDetails user = null;

		try {

			//              .
			//       dao  JDBC      
			DbUser dbUser = userDAO.getDatabase(username);

			// Populate the Spring User object with details from the dbUser
			// Here we just pass the username, password, and access level
			// getAuthorities() will translate the access level to the correct
			// role type

			user = new User(dbUser.getUsername(), dbUser.getPassword()
					.toLowerCase(), true, true, true, true,
					getAuthorities(dbUser.getAccess()));

		} catch (Exception e) {
			logger.error("Error in retrieving user");
			throw new UsernameNotFoundException("Error in retrieving user");
		}

		return user;
	}

	/**
	 *         
	 * 
	 * @param access
	 * @return
	 */
	public Collection getAuthorities(Integer access) {

		List authList = new ArrayList(2);

		//          ROLE_USER  
		logger.debug("Grant ROLE_USER to this user");
		authList.add(new GrantedAuthorityImpl("ROLE_USER"));

		//     access 1.   ROLE_ADMIN  
		if (access.compareTo(1) == 0) {
			logger.debug("Grant ROLE_ADMIN to this user");
			authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		}

		return authList;
	}
}

13コントローラjava
package com.demo.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("auth")
public class LoginController {
	protected static Logger logger = Logger.getLogger("controller");

	/**
	 *       
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String getLoginPage(
			@RequestParam(value = "error", required = false) boolean error,
			ModelMap model) {

		logger.debug("Received request to show login page");

		if (error == true) {
			// Assign an error message
			model.put("error",
					"You have entered an invalid username or password!");
		} else {
			model.put("error", "");
		}
		return "loginpage";
	}

	/**
	 *           
	 * 
	 * @return
	 */
	@RequestMapping(value = "/denied", method = RequestMethod.GET)
	public String getDeniedPage() {

		logger.debug("Received request to show denied page");

		return "deniedpage";
	}
}

このコントローラには2つのmappingマッピングがあります
main/common
main/admin
Spring Securityフレームワークと同様にログインに成功した人はmain/commonにアクセスできますが、main/adminにアクセスできるのはadmin権限を持つユーザーだけです.
 
14コントローラMainController.java
package com.demo.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/main")
public class MainController {
	protected static Logger logger = Logger.getLogger("controller");

	/**
	 *    commonpage  
	 * 
	 * @return
	 */
	@RequestMapping(value = "/common", method = RequestMethod.GET)
	public String getCommonPage() {
		logger.debug("Received request to show common page");
		return "commonpage";
	}

	/**
	 *    adminpage  
	 * 
	 * @return
	 */
	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String getAadminPage() {
		logger.debug("Received request to show admin page");
		return "adminpage";

	}

}

四、運行結果
1 spring-security-demoプログラムの起動
Spring Security入门Demo_第2张图片
 
2ブラウザに入力http://localhost:8080/spring-security-demo/auth/login
Spring Security入门Demo_第3张图片
 
3ユーザー名adminパスワードadminを入力し、「Login」ボタンをクリックする
Spring Security入门Demo_第4张图片
Spring Security入门Demo_第5张图片  
4「Go AdminPage」リンクをクリックすると、権限があるので管理者ページが表示されます
Spring Security入门Demo_第6张图片
 
5「ログオンを終了」をクリックし、ログオンページに戻る
Spring Security入门Demo_第7张图片
 
6ユーザー名userパスワードuserを入力してログインする
Spring Security入门Demo_第8张图片
Spring Security入门Demo_第9张图片  
7 Go AdminPageリンクをクリックすると、権限がないので、権限が足りないというヒントが表示されます
Spring Security入门Demo_第10张图片
 
8ログインを終了し、ログインページに戻る
Spring Security入门Demo_第11张图片
 
五、ソースコードのダウンロードアドレス
CSDN: http://download.csdn.net/detail/haishu_zheng/9555916
Github: https://github.com/zhenghaishu/Spring-Security-Demo