SpringBoot整合SpringSecurity

首先導入相關的依賴到pom.xml中:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

編寫相應的配置類

@EnableWebSecurity     //它裏面包含了@Configuration
public class MysecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定製請求的授權規則
		//也就是VIP1角色只能訪問/level1/下
        http.authorizeRequests().antMatchers("/").permitAll().
                antMatchers("/level1/**").hasRole("VIP1").
                antMatchers("level2/**").hasRole("VIP2").
                antMatchers("level3/**").hasRole("VIP3");

       /* 開啓自動配置的登陸功能
        1,/Login來到登陸頁
        2, 重定向到/Login?error表示登陸失敗*/
         http.formLogin();  //http.formLogin().loginPage("/userlogin"); 自己的登陸頁
         http.formLogin().usernameParameter("user").passwordParameter("psw").loginPage("/userlogin");
         //form表單中input name='user'   input name='psw'  分別對應登陸賬號密碼輸入框
        //如果沒有權限就會來登錄頁面
        //指定註銷成功後到哪個鏈接
        http.logout().logoutSuccessUrl("/");
        http.rememberMe(); //記住我
		http.rememberMe().rememberMeParameter("menber");  //和上面一樣的
    }
//定義認證規則,登陸賬戶密碼以及角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456")
                .roles("VIP1","VIP2")
                .and().withUser("lisi").password("123456").roles("VIP3","VIP2");
    }
}

thymeleaf整合SpringSecurity
pom.xml中加入:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

html文件,有些登陸顯示,有些沒有登錄顯示

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<div sec:authorize="!isAuthenticated()">請登陸</div>
<div sec:authorize="isAuthenticated()"><span sec:authentication="name"></span>您好</div>
<div sec:authorize="hasRole('VIP1')">
    此div只對VIP1可見
</div>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章