1. 程式人生 > >SpringBoot整合Spring-Security

SpringBoot整合Spring-Security

1、新增依賴

// 新增spring security依賴
	compile('org.springframework.boot:spring-boot-starter-security')
	// 新增Thymeleaf spring security依賴
	compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')

2、整合介面WebSecurityConfigurerAdapter

import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * 安全配之類
 * @author Administrator
 *
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	/**
	 * 自定義配置
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() // 都可以訪問
			.antMatchers("/users/**").hasRole("ADMIN") // 需要相應的角色才能訪問
			.and()
			.formLogin() // 基於表單Form登入驗證
			.loginPage("/login").failureUrl("/login-error");//自定義登入介面
	}
	
	/**
	 * 認證管理資訊
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
		auth.inMemoryAuthentication() // 認證資訊儲存於記憶體中
			.withUser("waylau").password("123456").roles("ADMIN");
	}
}

3、頁面運用

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
<!-- Page Content -->
<div class="container blog-content-container">

    <div sec:authorize="isAuthenticated()">
    	<p>已有使用者登入</p>
    	<p>登入的使用者為:<span sec:authentication="name"></span> </p>
    	<p>使用者角色為:<span sec:authentication="principal.authorities"></span> </p>
    </div>
	<div sec:authorize="isAnonymous()">
		<p>未有使用者登入</p>
	</div>

</div>
<!-- /.container -->


<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>