使用Spring Security和Thymeleaf实现访问控制

版权声明:原创文章,未经允许,禁止转载! https://blog.csdn.net/weixin_36512652/article/details/82226036
  • 引入相关依赖
  <!--引入thymeleaf与Spring Security整合的依赖-->
   <dependency>
       <groupId>org.thymeleaf.extras</groupId>
       <artifactId>thymeleaf-extras-springsecurity4</artifactId>
       <version>3.0.2.RELEASE</version>
   </dependency>

   <!--引入Spring Security依赖-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>

   <!--引入Thymeleaf依赖-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
  • 创建自定义WebSecurityConfigurerAdapter并重写configure方法
@EnableWebSecurity
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    //拦截请求
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置哪些url允许被某种角色访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/bronze").hasRole("英勇黄铜")
                .antMatchers("/silver").hasRole("不屈白银")
                .antMatchers("/gold").hasRole("荣耀黄金")
                .antMatchers("/platinum").hasRole("华贵铂金")
                .antMatchers("/diamond").hasRole("璀璨钻石")
                .antMatchers("/master").hasRole("超凡大师")
                .antMatchers("/challenger").hasRole("最强王者");

        //启用登录功能,可以使用默认的登录页,这里使用自定义的login.html页面
        http.formLogin().loginPage("/login");

        //启用注销功能,(需要提供一个action为/logout的form)并设置注销后访问的url,这里注销后跳转到首页
        http.logout().logoutSuccessUrl("/");

        //启用rememberMe功能,将用户信息保存在cookie中
        http.rememberMe();
    }

    //授权认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //inMemoryAuthentication表示使用基于内存的验证,还可以使用基于数据库的验证等,使用BCrypt编码对密码进行加密
        //,否则报错java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("bronze")
                .password(new BCryptPasswordEncoder().encode("0110")).roles("英勇黄铜")
                .and().withUser("silver").password(new BCryptPasswordEncoder()
                .encode("0110")).roles("不屈白银").and().withUser("gold")
                .password(new BCryptPasswordEncoder().encode("0110")).roles("荣耀黄金")
                .and().withUser("platinum").password(new BCryptPasswordEncoder()
                .encode("0110")).roles("华贵铂金").and().withUser("diamond")
                .password(new BCryptPasswordEncoder().encode("0110")).roles("璀璨钻石")
                .and().withUser("master").password(new BCryptPasswordEncoder()
                .encode("0110")).roles("超凡大师").and().withUser("challenger")
                .password(new BCryptPasswordEncoder().encode("0110")).roles("最强王者");
    }
}
  • 主页显示
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

<div align="center" style="margin-top: 15px" sec:authorize="!isAuthenticated()">
    <h4 style="color: blue;">欢迎您,亲爱的召唤师!<a th:href="@{/login}"> 请登录</a></h4>
</div>

<div align="center" style="margin-top: 15px" sec:authorize="isAuthenticated()">
    <h4 style="color: blue;">召唤师 <span sec:authentication="name"></span>
        ! 您的段位为:<span sec:authentication="principal.authorities"></span>
    </h4>
    <form th:action="@{/logout}" method="post">
        <input type="submit" th:value="注销登录">
    </form>
</div>

<div align="center" style="margin-top: 100px" sec:authorize="hasRole('英勇青铜')">
    <a th:href="@{/bronze}">点击领取英勇青铜段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('不屈白银')">
    <a th:href="@{/silver}">点击领取不屈白银段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('荣耀黄金')">
    <a th:href="@{/gold}">点击领取荣耀黄金段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('华贵铂金')">
    <a th:href="@{/platinum}">点击领取华贵铂金段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('璀璨钻石')">
    <a th:href="@{/diamond}">点击领取璀璨钻石段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('超凡大师')">
    <a th:href="@{/master}">点击领取超凡大师段位奖励</a>
</div>
<div align="center" style="margin-top: 100px" sec:authorize="hasRole('最强王者')">
    <a th:href="@{/challenger}">点击领取最强王者段位奖励</a>
</div>

</body>
</html>
  • 点击领取奖励页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>英勇黄铜</title>
</head>
<body>

<div align="center" style="margin-top: 20px">
    <a th:href="@{/}">返回首页</a>
</div>

<div align="center" style="margin-top: 100px">
    <h3>您在本赛季段位为:<span style="color: aqua;font-style: italic">英勇黄铜</span></h3>
    <h4>获得皮肤奖励:<span style="color: peru">锈迹斑斑 布里茨</span></h4>
</div>

</body>
</html>
  • 自定义登录页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<div align="center" style="margin-top: 60px">
    <form th:action="@{/login}" method="post">
        <p>
            <label>Username</label>
            <input type="text" th:name="username">
        </p>
        <p>
            <label>Password</label>
            <input type="password" th:name="password">
        </p>
        <p>
            <label>Remember Me</label>
            <input type="checkbox" th:name="remember-me">
        </p>
        <div align="center">
            <input type="submit" th:value="登录">
        </div>
    </form>
</div>

</body>
</html>
测试结果:
  • 首页
    首页

  • 登录页,点击Remember Me下次访问不需要重新登录
    登录页

  • 登录成功
    登录成功

  • 奖励页面
    奖励页面

猜你喜欢

转载自blog.csdn.net/weixin_36512652/article/details/82226036