Spring Security進行安全控制
文章內容來自於:http://blog.didispace.com/springbootsecurity/,作者:程序員DD
文章主要用於自己學習SpringBoot,方便以後的查詢
Spring Security有點類似攔截器
1.添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.在與Application.java同級目錄下創建WebSecurity.java
@Configuration //通過@Configuration註解,讓Spring來加載該類配置
@EnableWebSecurity //通過@EnableWebSecurity直接來啓用WebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //授權請求 --> 定義哪些URL需要被保護、哪些不需要被保護。
//例如指定了/和/home不需要任何認證就可以訪問,其他路徑必須通過身份認證
.antMatchers("/","/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin() //通過formLogin()定義當需要用戶登陸的時候,轉到的登陸頁面
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
/*
http.授權管理()
.螞蟻匹配者().許可所有()
.任何請求().認證()
.以及()
.表單登陸()
.登陸頁面()
.許可所有()
.以及()
.登出()
.許可所有()
*/
}
/**
* 在內存中創建了一個用戶,該用戶的名稱爲user,密碼爲passwrod,用戶角色爲USER
* @param auth
* @throws Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
- 通過
@EnableWebSecurity
註解開啓Spring Security的功能 - 繼承
WebSecurityConfigurerAdapter
。並重寫它的方法來設置一些web安全的細節 configure(HttpSecurity http)
方法
- 通過
authorizeRequests()
定義哪些URL需要被保護、哪些不需要被保護。例如以上代碼指定了/
和/home
不需要任何認證就可以訪問,其他的路徑都必須通過身份驗證。 - 通過
formLogin()
定義當需要用戶登陸的時候,轉到的登陸頁面。
- 通過
configureGlobal(AuthenticationManagerBuilder auth)
方法,在內存中創建了一個用戶,該用戶的名稱user,密碼password,用戶角色爲USER
根據配置,Spring Security提供了一個過濾器來攔截請求並驗證用戶身份。如果用戶身份認證失敗,頁面就重定向到/login?error
,並且頁面中會展現相應的錯誤信息。若用戶想要註銷登錄,可以通過訪問/login?logout
請求,在完成註銷之後,頁面展現相應的成功消息。