SpringBoot整合springsecurity

目錄

1、pom文件

<dependencies>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</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.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

2、靜態資源

跳轉到目錄
在這裏插入圖片描述
1.html, 其他x.html都一樣
在這裏插入圖片描述
welcome.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 align="center">歡迎光臨武林祕籍管理系統</h1>
	<div sec:authorize="!isAuthenticated()">
		<h2 align="center">遊客您好,如果想查看武林祕籍 <a th:href="@{/userlogin}">請登錄</a></h2>
	</div>
	<div sec:authorize="isAuthenticated()">
		<h2><span 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>
</html>

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<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="checkbox" name="remeber"> 記住我<br/>
			<input type="submit" value="登陸">
		</form>
	</div>
</body>
</html>

3、MySecurityController

跳轉到目錄

@Controller
public class MySecurityController {
    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;
    }
}

4、自定義SpringSecurity的配置類(重點)

跳轉到目錄

@EnableWebSecurity //開啓WebSecurity模式
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //定製請求的授權規則
        // 不同的角色可以訪問的權限不同
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //開啓自動配置的登陸功能,效果,如果沒有登陸,沒有權限就會來到登陸頁面
        //1/login來到登陸頁
        //2、重定向到/login?error表示登陸失敗
        //3、更多詳細規定
        //4、默認post形式的 /login代表處理登陸
        //5、一但定製loginPage;那麼 loginPage的post請求 /userlogin就代表處理登陸
        http.formLogin().usernameParameter("user").passwordParameter("pwd")
                .loginPage("/userlogin");



        //開啓自動配置的註銷功能。
        //1、訪問 /logout 表示用戶註銷,清空session
        //2、註銷成功會返回 /login?logout 頁面;
        http.logout().logoutSuccessUrl("/");//設置註銷成功以後來到首頁


        //開啓記住我功能
        //登陸成功以後,將cookie發給瀏覽器保存,以後訪問頁面帶上這個cookie,只要通過檢查就可以免登錄
        //點擊註銷會刪除cookie
        http.rememberMe().rememberMeParameter("remeber");
    }

    //定義認證規則
    // 需要對密碼進行加密 PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 這些數據正常應該從數據庫中讀
        // 給不同的用戶設置不同的角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123")).roles("vip2", "vip3")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
                .and()
                .withUser("zy").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3");

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章