1. 程式人生 > >SpringBoot+SpringSecurity中自定義介面卡簡單例子

SpringBoot+SpringSecurity中自定義介面卡簡單例子

最近閒來無事,熟悉公司的專案框架的時候,發現公司是用的spring boot整合spring security來控制使用者登入以及使用者角色,許可權等。之前只用過apache shiro,對spring security的瞭解甚少,只知道它提供的功能比shiro更強大,所以寫下此文章,記錄一下自己對spring security的學習過程。

spring官網上面有這麼一段demo,它給我們說明了spring security自定義介面卡的部分功能:

package org.springframework.security.samples.config;

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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
				.antMatchers("/css/**", "/index").permitAll()		
				.antMatchers("/user/**").hasRole("USER")			
				.and()
			.formLogin()
				.loginPage("/login").failureUrl("/login-error");	
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.inMemoryAuthentication()
				.withUser("user").password("password").roles("USER");
	}
}

1. / css / **/ index匹配的請求是完全可訪問的

2./ user / **匹配的請求要求使用者進行身份驗證,並且必須與USER角色相關聯

3.使用自定義登入頁面和失敗URL啟用基於表單的身份驗證

4.configure方法重寫了父類的方法,裡面定義了spring security應該忽略或者攔截驗證的一些url路徑。

5. configureGlobal方法是確定您要如何進行身份驗證,上面的demo是在記憶體中建立了一個使用者,該使用者的名稱為user,密碼為password,使用者角色為USER。