準備工做html
首先,構建一個簡單的Web工程,以用於後續添加安全控制,也能夠用以前Chapter3-1-2作爲基礎工程。若對如何使用Spring Boot構建Web應用,能夠先閱讀《Spring Boot開發Web應用》一文。web
Web層實現請求映射spring
@Controller public class HelloController {安全
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/hello")
public String hello() {
return "hello";
}
複製代碼
} /:映射到index.html /hello:映射到hello.html 實現映射的頁面app
src/main/resources/templates/index.htmlide
點擊 這裏 打個招呼吧spring-boot
src/main/resources/templates/hello.htmlweb安全
整合Spring Securitypost
在這一節,咱們將對/hello頁面進行權限控制,必須是受權用戶才能訪問。當沒有權限的用戶訪問後,跳轉到登陸頁面。ui
添加依賴
在pom.xml中添加以下配置,引入對Spring Security的依賴。
... org.springframework.boot spring-boot-starter-security ... Spring Security配置建立Spring Security的配置類WebSecurityConfig,具體以下:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@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配置以後,咱們還缺乏登陸的相關內容。
HelloController中新增/login請求映射至login.html
@Controller public class HelloController {
// 省略以前的內容...
@RequestMapping("/login")
public String login() {
return "login";
}
複製代碼
} 新增登陸頁面:src/main/resources/templates/login.html
根據配置,Spring Security提供了一個過濾器來攔截請求並驗證用戶身份。若是用戶身份認證失敗,頁面就重定向到/login?error,而且頁面中會展示相應的錯誤信息。若用戶想要註銷登陸,能夠經過訪問/login?logout請求,在完成註銷以後,頁面展示相應的成功消息。
到這裏,咱們啓用應用,並訪問http://localhost:8080/,能夠正常訪問。可是訪問http://localhost:8080/hello的時候被重定向到了http://localhost:8080/login頁面,由於沒有登陸,用戶沒有訪問權限,經過輸入用戶名user和密碼password進行登陸後,跳轉到了Hello World頁面,再也經過訪問http://localhost:8080/login?logout,就能夠完成註銷操做。
爲了讓整個過程更完成,咱們能夠修改hello.html,讓它輸出一些內容,並提供「註銷」的連接。
源碼來源:http://minglisoft.cn/honghu/technology.html