ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

第十三章:(2)Spring Boot 与 安全 之 SpringBoot + SpringSecurity + Thymeleaf

2022-01-06 20:31:09  阅读:165  来源: 互联网

标签:http SpringBoot Spring Boot antMatchers hasRole 登陆 login 注销


一、使用 Spring Security

  1、引入依赖

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

 

  2、编写 Spring Security 配置类

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {}

 

 

二、定制授权规则

  定义哪些url由哪些角色可以进行访问:

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        //开启自动配置的登录功能,如果没有登陆,没有权限就会来到登陆页面
        http.formLogin();
        //1、/login 来到登陆页
        //2、重定向到 /login?error 表示登陆失败
        //3、更多详细规定
    }
}

 

 

三、定制认证规则

  定义用户名,密码和角色:

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        //开启自动配置的登录功能,如果没有登陆,没有权限就会来到登陆页面
        http.formLogin();
        //1、/login 来到登陆页
        //2、重定向到 /login?error 表示登陆失败
        //3、更多详细规定
    }


    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password("123456").roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2", "VIP3")
                .and()
                .withUser("wangwu").password("123456").roles("VIP1", "VIP3");
    }
}

 

 

四、注销功能

  开启自动配置的注销功能:

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        //开启自动配置的登录功能,如果没有登陆,没有权限就会来到登陆页面
        http.formLogin();
        //1、/login 来到登陆页
        //2、重定向到 /login?error 表示登陆失败
        //3、更多详细规定


        //开启自动配置的注销功能
        //1 访问 /logout 表示用户注销,清空 session
        //2.注销成功返回 /login?logout 页面,可以使用 logoutSuccessUrl() 设置注销之后要去的url
        http.logout().logoutSuccessUrl("/");

    }
}

 

  添加注销按钮

<form th:action="@{/logout}" method="post">
    <input type="submit" value="注销">
</form>

 

 

五、权限控制

  1、使用 Thymeleaf 与 SpringSecurity 整合依赖

<properties>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
    <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>
<dependencies>
    <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>
    <!--security 模块-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

 

  2、使用 Thymeleaf 实现权限控制

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<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>

 

六、记住我功能

  开启自动配置的"记住我"功能:

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        //开启自动配置的登录功能,如果没有登陆,没有权限就会来到登陆页面
        http.formLogin();
        //1、/login 来到登陆页
        //2、重定向到 /login?error 表示登陆失败
        //3、更多详细规定


        //开启自动配置的注销功能
        //1 访问 /logout 表示用户注销,清空 session
        //2.注销成功返回 /login?logout 页面,可以使用 logoutSuccessUrl() 设置注销之后要去的url
        http.logout().logoutSuccessUrl("/");


        //开启记住我功能
        http.rememberMe();
        //登录成功以后,将 cookie 发送给浏览器保存,以后访问页面带上这个 cookie,只要通过检查就可以免登录
        //点击注销会删除 cookie

    }
}

 

  通过 cookie 来实现的。

 

七、定制登录页面

  自定义登录页面及 "记住我"功能:

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        //开启自动配置的登录功能,如果没有登陆,没有权限就会来到登陆页面
        http.formLogin().usernameParameter("user")
                .passwordParameter("pwd")
                .loginPage("/userlogin");
        //1、/login 来到登陆页
        //2、重定向到 /login?error 表示登陆失败
        //3、更多详细规定
        //4. 默认 post 形式的/login代表处理登录
        //5、一旦定制 loginPage,那么 loginPage 的 post 请求就是登录


        //开启自动配置的注销功能
        //1 访问 /logout 表示用户注销,清空 session
        //2.注销成功返回 /login?logout 页面,可以使用 logoutSuccessUrl() 设置注销之后要去的url
        http.logout().logoutSuccessUrl("/");


        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
        //登录成功以后,将 cookie 发送给浏览器保存,以后访问页面带上这个 cookie,只要通过检查就可以免登录
        //点击注销会删除 cookie

    }


    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password("123456").roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2", "VIP3")
                .and()
                .withUser("wangwu").password("123456").roles("VIP1", "VIP3");
    }
}

 

  定义控制器方法:

    /**
     * 登陆页
     * @return
     */
    @GetMapping("/userlogin")
    public String loginPage() {
        return PREFIX+"login";
    }

 

  定义登录页面:

<!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="remember">记住我<br/>
            <input type="submit" value="登陆">
        </form>
    </div>
</body>
</html>

 

  修改登录地址:

<div sec:authorize="!isAuthenticated()">
    <!--没有认证-->
    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>

 

标签:http,SpringBoot,Spring,Boot,antMatchers,hasRole,登陆,login,注销
来源: https://www.cnblogs.com/niujifei/p/15772717.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有