ss-SpringSecurity角色分配登录退出 (SpringSecurity环境搭建,spring-boot)

170 阅读1分钟

场景

分配3个角色 vip1 / vip2 / vip3,对应3个帐号有不同的权限

默认登录页 http://localhost:8080/toLogin

退出之后 跳转到 首页 http://localhost:8080/toLogin

(SpringSecurity环境搭建,spring-boot)

版本

spring-boot-starter-security 2.7.0

thymeleaf-extras-springsecurity5 3.0.4.RELEASE

pom.xml

//jetbrains://idea/navigate/reference?project=sprintboot&path=spingboot-06-security/pom.xml:23:3       
       
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- security-thymeleaf整合包 -->
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>


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

配置类

//SecurityConfig.php
//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/spingboot06security/config/SecurityConfig.java:15:7

//AOP  : 拦截器
@EnableWebSecurity
public class SecurityConfig 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");

       //没有权限默认会到登通页面,需要开启登录的页面
        //login
        //定制登录页 .loginPage("/toLogin")
       http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

       //防止网站 :get post
        http.csrf().disable(); //关闭CSRF功能

       //注销,开启了注销功能,跳到首页
       http.logout().logoutSuccessUrl("/");

       //开启记住我功能,cookie,默认保存2周
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证 springboot 2.1.X可以直接使用|
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据库中读
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("ken").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3");
    }
}

控制类

//RouteController
//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/spingboot06security/controller/RouteController.java:14:1


@Controller
public class RouteController {

    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "view/login";
    }

    @GetMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "view/level1/"+id;
    }

    @GetMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "view/level2/"+id;
    }

    @GetMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "view/level3/"+id;
    }

}

视图文件

└─templates
    │  index.html
    │
    └─view
        │  login.html
        │
        ├─level1
        │      1.html
        │      2.html
        │      3.html
        │
        ├─level2
        │      1.html
        │      2.html
        │      3.html
        │
        └─level3
                1.html
                2.html
                3.html

 
---------- index.html  ---------- 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div th:fragment="nav-menu">
   <!-- 如果未登录  -->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">登录</a>
    </div>

    <!-- 如果资条:用户名,注销 -->
    <div sec:authorize="isAuthenticated()">
        <a class="item">
            用户名:<span sec:authentication="name">  </span>
            角色:<span sec:authentication="principal.authorities">  </span>
        </a>
    </div>
    <div sec:authorize="isAuthenticated()">
        <a class="item" th:href="@{/logout}">退出</a>
    </div>
</div>

<ul>
    <li sec:authorize="hasRole('vip1')">
        <a href="/level1/1">vip1 -1</a>
        <a href="/level1/2">vip1 -2</a>
        <a href="/level1/2">vip1 -2</a>
    </li>
    <li sec:authorize="hasRole('vip2')">
        <a href="/level2/1">vip2 -1</a>
        <a href="/level2/2">vip2 -2</a>
        <a href="/level2/2">vip2 -2</a>
    </li>
    <li sec:authorize="hasRole('vip3')">
        <a href="/level3/1">vip3 -1</a>
        <a href="/level3/2">vip3 -2</a>
        <a href="/level3/2">vip3 -2</a>

    </li>
</ul>
</body>
</html>


---------- login.html  ---------- 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    用户名:<input type="text" name="user"><br />
    密码:<input type="password" name="pwd"><br />
    <input type="checkbox" name="remember"> 记住我<br />
    <input type="submit">
</form>
</body>
</html>

---------- 1.html 其它一样 ---------- 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:replace="~{index::nav-menu}"></div>
level1 - 1
</body>
</html>