window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

SpringBoot-08 SpringSecurity

SpringBoot-08 SpringSecurity

创建了一个新项目,创建时选择导入starter-web

1.环境搭建

1.1 导入thymeleaf

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

1.2 导入静态资源

  • cssjs这样的静态资源导入到static文件夹下
  • 前端页面导入到templates文件夹下
1

如果需要静态资源,可以私信我或者发邮件 moyu_zc@163.com

1.3 关闭thymeleaf缓存

spring.thymeleaf.cache=false

1.4 测试运行

2 3 4

2.用户认证和授权

2.1 导入依赖

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

2.2 创建Config

创建一个config文件夹:

@EnableWebSecurity
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")   //对于level2文件夹下的页面需要vip2才能登录
                .antMatchers("/level3/**").hasRole("vip3");  //对于level3文件夹下的页面需要vip3才能登录
        //如果没有权限,进入登录页面,这是Security内部自带的
        http.formLogin();
    }
}
5

2.3 认证

就是给予下面这些用户相应的权限。

//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("zc").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
        .and()
        .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
        .and()
        .withUser("test").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
}

大家可以自行测试。

3.注销及权限控制

3.1 注销

1.开启注销功能

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/").permitAll()                //对于主页面都可以登录
        .antMatchers("/level1/**").hasRole("vip1")   //对于level1文件夹下的页面需要vip1才能登录
        .antMatchers("/level2/**").hasRole("vip2")   //对于level2文件夹下的页面需要vip2才能登录
        .antMatchers("/level3/**").hasRole("vip3");  //对于level3文件夹下的页面需要vip3才能登录
    //如果没有权限,进入登录页面,这是Security内部自带的
    http.formLogin();

    //注销功能
    http.logout().logoutSuccessUrl("/");
}

2.添加注销按钮

<!--登录注销-->
<div class="right menu">
    <!--未登录-->
    <a class="item" th:href="@{/toLogin}">
        <i class="address card icon"></i> 登录
    </a>
    <a class="item" th:href="@{/logout}">
        <i class="address card icon"></i> 注销
    </a>
</div>
6

3.2 权限控制

springboot 2.1.x版本以上不兼容这个标签,最好使用2.0.7及其以下的

1.加入thymeleaf、springsecurity整合依赖

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

2.增加对应的头部文件

xmlns:th="http://www.thymeleaf.org" 
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

3.修改前端页面

<!--登录注销-->
<div class="right menu">
    <!--未登录-->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i> 登录
        </a>
    </div>
    <div sec:authorize="isAuthenticated()">
        <a class="item" >
            用户名:<span sec:authentication="name"></span>
        </a>
        <a class="item" th:href="@{/logout}">
            <i class="address card icon"></i> 注销
        </a>
    </div>
</div>   

4.首页定制

4.1 登录页面

1.修改Config

http.formLogin().loginPage("/toLogin");

2.修改login页面的路径

<form th:action="@{/toLogin}" method="post">

如果想要自定义action,可以使用:

http.formLogin().loginPage("/toLogin").loginProcessingUrl("xxx");

如果前端form表单中的name与后端不一一对应,可以使用:

 http.formLogin().loginPage("/toLogin").usernameParameter("xxx").passwordParameter("xxx");

4.2 记住我

1.前端添加记住我选框

<div class="field">
    <input type="checkbox" name="remember">
</div>

2.修改Config

http.rememberMe().rememberMeParameter("remember");

个人博客为:
MoYu's HomePage
MoYu's Gitee Blog

posted @ 2021-04-02 11:43  MoYu-zc  阅读(105)  评论(0编辑  收藏  举报