springboot_SpringSecurity

本文介绍了如何在SpringBoot中配置和使用SpringSecurity进行环境搭建,包括导包、修改配置、导入静态资源和编写Controller。接着详细阐述了用户认证和授权过程,如重写认证方法,以及解决首页显示所有用户功能的问题。通过整合Thymeleaf与Spring Security实现了权限控制。最后,讨论了开启“记住我”功能以及定制首页的两种方式,并提出了表单提交后自动跳转到index页面的疑问。

环境搭建

1.导包

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

2.修改配置文件

#关闭模板引擎缓存
spring.thymeleaf.cache=false

3.导入静态资源
在这里插入图片描述
4.编写controller

@Controller//这里不能写@Responsebody  否则返回的就是字符串
public class RouterController {
    @RequestMapping({"/", "/index"})
    public String index(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id")int id){
        return "views/level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id")int id){
        return "views/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id")int id){
        return "views/level3/"+id;
    }
}

在这里插入图片描述

用户认证和授权

在这里插入图片描述
1.导包

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

编写config

package com.kuang.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//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");
        //如果没有权限默认会到登录页面,需要开启登录的页面
        http.formLogin();
        //开启注销功能
        http.logout();
//                     .logoutSuccessUrl(“/index”)指定注销成功跳转到哪个页面
    }
}

添加注销

<!--如果未登录 :要有登录按钮-->
                <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon"></i> 登录
                </a>
<!--                如果已登录:登录名,注销-->
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>

在这里插入图片描述
开启登录页面后,没有权限自动跳转到登录页面(此页面不是我们的)
在这里插入图片描述
现在写重写认证方法

    //认证 在springboot 2.1.x中可以直接使用 新版需要将密码加密才能使用
    //密码编码:passwordEncoding
    //spring security 5.+ 新增了很多加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //inMemoryAuthentication()从内存中拿,jdbcAuthentication()从数据库拿
        //可以拼接多个用户,用and()连接
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3","vip2","vip1");
    }

倘若从数据库拿取用户名和密码
在这里插入图片描述

现在有一个问题,首页显示了所有用户的功能,包含登录用户没有权限的功能,这显然是不合理的,怎么解决呢?将Thymeleaf与spring security整合。

整合Thymeleaf与spring security(权限控制)

1.导包

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

添加命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
            <!--登录注销-->
            <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>
                        角色:<span sec:authentication="authorities"></span>
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                         <i class="sign-out icon"></i> 注销
                    </a>
                </div>

            </div>

成功
在这里插入图片描述
添加权限控制
在这里插入图片描述
成功
在这里插入图片描述

记住我及首页定制

1.开启记住我功能

        //开启记住我功能 cookie 默认保存两周 
        http.rememberMe();

在这里插入图片描述
2.定制首页
方式一

        //如果没有权限默认会到登录页面,需要开启登录的页面
        http.formLogin().loginPage("/toLogin");

在这里插入图片描述
方式二
在这里插入图片描述

        //如果没有权限默认会到登录页面,需要开启登录的页面
        http.formLogin().loginPage("/toLogin")//获取数据的页面
                .usernameParameter("username").passwordParameter("pwd")
                .loginProcessingUrl("/login");//实际请求的页面


        //开启记住我功能 cookie 默认保存两周
        http.rememberMe().rememberMeParameter("remember");
        //开启注销功能
        http.logout().logoutSuccessUrl("/index");
//                     .logoutSuccessUrl(“/index”)指定注销成功跳转到哪个页面
        //防止网站攻击,get,post,默认开启 我们现在关闭csrf功能
//        http.csrf().disable();

有一个疑问,为什么表单提交后,认证成功后它就到了index页面?我们并没有配置 是自动到”/“下吗

Thymeleaf - Spring Security integration modules [Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Status This is a thymeleaf extras module, not a part of the Thymeleaf core (and as such following its own versioning schema), but fully supported by the Thymeleaf team. This repository contains two projects: thymeleaf-extras-springsecurity3 for integration with Spring Security 3.x thymeleaf-extras-springsecurity4 for integration with Spring Security 4.x Current versions: Version 3.0.2.RELEASE - for Thymeleaf 3.0 (requires Thymeleaf 3.0.3+) Version 2.1.3.RELEASE - for Thymeleaf 2.1 (requires Thymeleaf 2.1.2+) License This software is licensed under the [Apache License 2.0] (http://www.apache.org/licenses/LICENSE-2.0.html). Requirements (3.0.x) Thymeleaf 3.0.0+ Spring Framework version 3.0.x to 4.3.x Spring Security version 3.0.x to 4.2.x Web environment (Spring Security integration cannot work offline) Maven info groupId: org.thymeleaf.extras artifactId: Spring Security 3 integration package: thymeleaf-extras-springsecurity3 Spring Security 4 integration package: thymeleaf-extras-springsecurity4 Distribution packages Distribution packages (binaries + sources + javadoc) can be downloaded from SourceForge. Features This module provides a new dialect called org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect or org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect (depending on the Spring Security version), with default prefix sec. It includes: New expression utility objects: #authentication representing the Spring Security authentication object (an object implementing the org.springframework.security.core.Authentication interface). #authorization: a expression utility object with methods for checking authorization based on expressions, URLs and Access Control Lists. New attributes: sec:authentication="prop" outputs a prop property of the authentication object, similar to the Spring Secu
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值