1. 程式人生 > >springboot和spring security簡單使用

springboot和spring security簡單使用

整理自是尚矽谷springboot高階

配置類(最重要的了)

@EnableWebSecurity//這個註解組合註解裡面有@Configuration 所以不要配置@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //重寫認證方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/").permitAll() //放行這個請求
            .antMatchers("/level1/**").hasRole("vip1") //level1下的頁面需要vip1這個角色才可以訪問
            .antMatchers("/level2/**").hasRole("vip2")
            .antMatchers("/level3/**").hasRole("vip3");

        //開啟自動配置的登入功能,就是你沒登陸或者沒有許可權,給你建立一個登入頁面
           // http.formLogin()
        //開啟自動配置的登入功能,用自己的登入頁 路徑loginPage("/userlogin")
        //passwordParameter  usernameParameter 自定義表單的name值(預設username password)
        http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");
        //設定退出及退出成功後的頁面(前臺需要post方法提交)
      /*  <form th:action="@{/logout}" method="post">
		    <input type="submit" value="登出"/>
	       </form>*/
         http.logout().logoutSuccessUrl("/");
         //開啟記住我功能,前端會添加個複選框記住我和實現記住我功能,無需自己實現
         http.rememberMe().rememberMeParameter("rember");

    }

   //重寫授權方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //建立一個使用者,給其賦值和賦予角色多個角色逗號隔開
        auth.inMemoryAuthentication()
             .withUser("zs").password("123").roles("vip1")
             .and()
             .withUser("ls").password("123").roles("vip2","vip1")
             .and()
             .withUser("ww").password("123").roles("vip3","vip1") ;
    }
  /*  @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }*/
}

pom檔案

        <!---選擇1.x版本--->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
                <!---選擇3版本-->
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
             <!---選擇3版本-->
		<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
            <!---選擇2版本-->
		<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

welcom.html

<!---名稱空間有寫程式碼提示---->
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

<body>
<h1 align="center">歡迎光臨武林祕籍管理系統</h1>
<div sec:authorize="!isAuthenticated()">
	<h2 align="center">遊客您好,如果想檢視武林祕籍 <a th:href="@{/login}">請登入</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
	<h2>歡迎您: <span style="color: red" sec:authentication="name"></span> 您的角色有 <span  sec:authentication="principal.authorities"></span></h2>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="登出"/>
	</form>
</div>
<hr>

<div sec:authorize="hasRole('vip1')">
	<h3>普通武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level1/1}">羅漢拳</a></li>
		<li><a th:href="@{/level1/2}">武當長拳</a></li>
		<li><a th:href="@{/level1/3}">全真劍法</a></li>
	</ul>
</div>

<div sec:authorize="hasRole('vip2')">
	<h3>高階武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level2/1}">太極拳</a></li>
		<li><a th:href="@{/level2/2}">七傷拳</a></li>
		<li><a th:href="@{/level2/3}">梯雲縱</a></li>
	</ul>
</div>
<div sec:authorize="hasRole('vip3')">
	<h3>絕世武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level3/1}">葵花寶典</a></li>
		<li><a th:href="@{/level3/2}">龜派氣功</a></li>
		<li><a th:href="@{/level3/3}">獨孤九劍</a></li>
	</ul>
</div>
</body>

 

自定義登入頁面

 

<body>
	<h1 align="center">歡迎登陸武林祕籍管理系統</h1>
	<hr>
	<div align="center">
		<form th:action="@{/userlogin}" method="post">
			使用者名稱:<input name="user"/><br>
			密碼:<input name="pwd"><br/>
			<input type="submit" value="登陸">
			<input type="checkbox" name="rember">記住我
		</form>
	</div>
</body>

這個level1,level2,level3目錄類似如此,沒啥內容命名相同即可

控制器,跳轉相關頁面(KungfuController)

@Controller
public class KungfuController {
	private final String PREFIX = "pages/";
	/**
	 * 歡迎頁
	 * @return
	 */
	@GetMapping("/")
	public String index() {
		return "welcome";
	}
	
	/**
	 * 登陸頁
	 * @return
	 */
	@GetMapping("/userlogin")
	public String loginPage() {
		return PREFIX+"login";
	}
	
	
	/**
	 * level1頁面對映
	 * @param path
	 * @return
	 */
	@GetMapping("/level1/{path}")
	public String level1(@PathVariable("path")String path) {
		return PREFIX+"level1/"+path;
	}
	
	/**
	 * level2頁面對映
	 * @param path
	 * @return
	 */
	@GetMapping("/level2/{path}")
	public String level2(@PathVariable("path")String path) {
		return PREFIX+"level2/"+path;
	}
	
	/**
	 * level3頁面對映
	 * @param path
	 * @return
	 */
	@GetMapping("/level3/{path}")
	public String level3(@PathVariable("path")String path) {
		return PREFIX+"level3/"+path;
	}


}

 

截圖