SpringBoot中Security

# Spring Boot Security #

## 1.如何使用Spring Security ##

1.导入Security依赖

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

2.编写Spring Security配置类

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

3.控制请求的访问权限,重写configure(HttpSecurity http)方法

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

        //开启自动配置的登录功能
        //login请求会自动生成一个登录页,如果登录失败会重定向到/login?error页面
        //默认的到登录页请求是get请求方式的/login请求,
        //默认处理登录请求是post方式的/login请求,由Spring Security自己处理
        //可以使用loginPage("/userLogin")修改默认登录页,如果修改了默认登录页,则需要修改默认处理登录请求,登录请求改为post方式的/userLogin
        //默认登录页的请求参数名为username和password,在新的登录页可以修改为这个,也可以使用
        //usernameParameter("user")和passwordParameter("pwd")来修改提交的参数名
        http.formLogin().loginPage("/userlogin")
                .usernameParameter("user")
                .passwordParameter("pwd");

        //访问/logout请求表示用户注销,清空session
        //注销,使用logoutSuccessUrl可以指定注销成功默认显示的页面,
        //如果不指定则默认回到login页面,默认调用/login?logout请求
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能,默认的input名称为remember-me可以使用
        // rememberMeParameter("remember")来修改参数名
        http.rememberMe().rememberMeParameter("remember");
    }

    <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>

4.定义认证规则 Spring Security5.x版本

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2").and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP3").and()
                .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3");
    }

    //inMemoryAuthentication()方法用来在内存中生成用户
    //withUser:生成的用户

5.定义认证规则 Spring Security5.x之前的版本

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

    //inMemoryAuthentication()方法用来在内存中生成用户
    //withUser:生成的用户

6.需要注意的是:

    我们使用的是Security自带的登录页面,在Spring Security5.x版本新增了多种加密方式,也改变了密码的格式.新版本的Spring Security使用的密码格式是:"{id}密码",前面的id是加密的方式,类似于下面的密码格式:

    {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG 
    {noop}password 
    {pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc 
    {scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=  
    {sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0

    程序获取密码的时候先获取id的值也就是加密的方式,如果没有加密的方式则会报There is no PasswordEncoder mapped for the id “null”错误,Spring Security 官方推荐的是使用bcrypt加密方式

    所以在内存中生成用户的时候在inMemoryAuthentication()后面加上了passwordEncoder(new BCryptPasswordEncoder()),在每个用户的生成密码上面添加了new BCryptPasswordEncoder().encode("123456")这串代码

    此处的解决方式是https://blog.csdn.net/canon_in_d_major/article/details/79675033这位博主写的,侵删


## 2.Spring Security和Thymeleaf整合 ##

1.pom.xml文件中导入依赖

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

2.在html的头文件中引入spring security路径

    xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

    使用isAuthenticated()判断是否登录

    sec:authentication="name":登录的用户名
    sec:authentication="principal.authorities":拥有的权限

    sec:authorize="hasRole('VIP1')":是否拥有VIP1权限

    <div sec:authorize="!isAuthenticated()">
        <!--th:href="@{/login}"-->
        <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>

    <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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值