SpringSecurity安全性框架實戰

你們好,本人最近在學習spring4,參考了書籍,寫了一些demo(基於Servlet3.0,JDK7.0,Spring4,Tomcat8),歡迎討論。html

在上個月發了一篇《Spring4純註解啓動》的博客http://www.javashuo.com/article/p-wjwzjchq-ma.htmljava

SpringSecurity是基於Spring的應用程序提供聲明式安全保護的安全性框架。我能力有限,沒法寫出一篇詳解,只能成功使用,邏輯大概明白而已,讓你們見笑了。web

Maven:spring

<!-- spring-security -->
		<dependency>
	        <groupId>org.springframework.security</groupId>
	        <artifactId>spring-security-web</artifactId>
	        <version>4.2.1.RELEASE</version>
	    </dependency>
	    <dependency>
		    <groupId>org.springframework.security</groupId>
		    <artifactId>spring-security-config</artifactId>
		    <version>4.2.1.RELEASE</version>
		</dependency>

主要類:(紅色框內)sql

----------------------------------數據庫

SpringSecurity藉助一系列ServletFilter來提供各類安全性功能。安全

DelegatingFilterProxy是一個特殊的ServletFilter,它自己所作的工做並很少,只是將工做委託給了一個javax.servlet.Fitler實現類,這個實現類註冊在Spring應用的上下文。cookie

它把Fitler的處理邏輯委託給Spring應用上下文中所定義的一個代理FitlerBean。框架

SecurityWebInitializer:ide

/**
 * 註冊DelegatingFilterProxy
 * @author zoe
 * 2017年1月17日
 * DelegatingFilterProxy是一個特殊的ServletFilter,它自己所作的工做並很少,只是將工做委託給了一個javax.servlet.Fitler實現類,這個實現類註冊在Spring應用的上下文。
 */
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {

}

SecurityConfig:

package com.spittr.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.stereotype.Repository;
import org.springframework.test.annotation.Repeat;

/**
 * SpringSecurity啓動配置類
 * @author zoe
 * 2017年1月17日
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired
	private DataSource dataSource;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		/**  第一種將用戶資料存儲在內存中   **/
//		auth.inMemoryAuthentication().withUser("user").password("123456").roles("USER").and().withUser("admin").password("admin").roles("USER","ADMIN");
		
		/**  第二種使用關係型數據庫  
		//這3個是安全框架默認的查詢,前提是你的表跟它預期的同樣,通常狀況不會,因此要重寫這類查詢
		//將默認sql查詢替換要遵循查詢的基本協議。全部查詢都將用戶名做爲惟一的參數。
		String DEF_USERS_BY_USERNAME_QUERY = "select username,password,enabled "
				+ "from users " + "where username = ?";
		String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select username,authority "
				+ "from authorities " + "where username = ?";
		String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "
				+ "from groups g, group_members gm, group_authorities ga "
				+ "where gm.username = ? " + "and g.id = ga.group_id "
				+ "and g.id = gm.group_id";
		
		//查詢用戶名,密碼,是否啓用等,用來進行用戶認證
		auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(DEF_USERS_BY_USERNAME_QUERY);
		//查詢用戶所授予的權限,用來進行鑑權  0或多條
		auth.jdbcAuthentication().dataSource(dataSource).authoritiesByUsernameQuery(DEF_AUTHORITIES_BY_USERNAME_QUERY);
		//查詢用戶羣組的成員所授予的權限 0或多條
		auth.jdbcAuthentication().dataSource(dataSource).groupAuthoritiesByUsername(DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY);
		**/
		
		/**  第三種使用自定義認證,隨意搭配方式   **/
		UserDetailsService userDetailsService = new SecurtityUserDetailService();
		auth.userDetailsService(userDetailsService);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();
		
		/**在authorizeRequests.antMatchers()的返回值中能夠繼續調用hasAnyAuthority()或者hasRole()這2個方法,
		看起來一個是權限,一個是角色,可是仔細研究,你會發現,hasRole只是hasAnyAuthority它的一個簡寫版
		因此在這個框架中,我認爲能控制到角色這一層**/
		//Specify that URLs require a particular authority.
		authorizeRequests.antMatchers("/form.do").hasAuthority("ROLL_ADMIN");
		//Shortcut for specifying URLs require a particular role. If you do not want to have "ROLE_" automatically inserted see hasAuthority(String).
		authorizeRequests.antMatchers("/form.do").hasRole("ADMIN");
		
		authorizeRequests.antMatchers("/form.do").authenticated();//authenticated()必須已經登陸了應用
		authorizeRequests.anyRequest().permitAll();//容許其餘請求經過
		http.formLogin().loginPage("/login.html").loginProcessingUrl("/login.do").defaultSuccessUrl("/index.html")//登陸首頁,默認驗證經過後登陸index.html,驗證請求/login.do
		.and().httpBasic()//開啓httpBasic認證
		.and().logout().logoutUrl("/logout.do").logoutSuccessUrl("/login.html")//登出後,跳轉login.html
		.and().rememberMe().tokenValiditySeconds(3600).key("securityKey")//記住我 cookies 中會記錄 一小時後失效 60*60
		.and().csrf().disable();//禁用CSRF保護功能
	}
}

SecurtityUserDetailService:

/**
 * 自定義用戶認證
 * @author zoe
 * 2017年1月17日
 */
public class SecurtityUserDetailService implements UserDetailsService {

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		//模擬admin權限
		authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		//模擬admin用戶
		SecurityUser securityUser = new SecurityUser("admin","admin",authorities);
		
		return securityUser;
	}

}

SecurityUser:

/**
 * 安全認證用戶
 * @author zoe
 * 2017年1月17日
 * 注意,在下方的一些boolean型的參數,默認是false,認證會失敗
 */
public class SecurityUser implements UserDetails {
	
	private String userName;
	private String password;

	private Collection<? extends GrantedAuthority> authorities;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public SecurityUser(String userName,String password){
		this.userName = userName;
		this.password = password;
	}
	
	public SecurityUser(String userName,String password,Collection<? extends GrantedAuthority> authorities){
		this.userName = userName;
		this.password = password;
		this.authorities = authorities;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	@Override
	public String getPassword() {
		// TODO Auto-generated method stub
		return this.password;
	}

	@Override
	public String getUsername() {
		// TODO Auto-generated method stub
		return this.userName;
	}

	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}

}

login.html:

<form action="/login.do" method="post">
				<div>
					<input type="text" name="username" class="username" placeholder="用戶名" autocomplete="off" />
				</div>
				<div>
					<input type="password" name="password" class="password" placeholder="密碼" oncontextmenu="return false" onpaste="return false" />
				</div>
				<div class="remember">
					<input type="checkbox" name='remember-me'/><span>下次自動登陸</span>
				</div>
				<button id="submit" type="submit">登陸</button>
			</form>

index.html:

<a href="/logout.do">登出</a>
相關文章
相關標籤/搜索