26.0、springboot-security注销以及权限控制、27.0、登录界面、网页“记住我”功能的实现

26.0、注销以及权限控制

        授权、认证、登录啥的在之前写的25.0文章里面

        开启注销功能,只需要在配置类中加上http.logout();即可,点击logout查看原码,可以看到源码中表示/logout请求可以执行注销功能,还可以附加上清除cookie的一些其他操作。

        点击logout查看原码,可以看到:

        http.logout().deleteCookies("remove").invalidateHttpSession(true);这个方法清除所有cookies(但是咱们一般不这么用,这里就不演示这个代码了)

        http.logout().logoutSuccessUrl("/index");方法设置一下注销后返回index主页

java配置类代码如下所示:

SecurityConfig 配置类文件

package com.hkl.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@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();
    }
    //认证,springboot2.1.x 可以直接使用~
    //密码加密编码处理:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多的加密的方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        这些认证的数据正常情况下应该从数据库里读取,但是由于我这里测试没有连接数据库,所以直接将数据写死。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("hkl").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("xiaolan").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");

    }
}

        但是我们发现主页显示的内容有一个问题:我们登录的用户拥有什么权限就应该显示相对应的内容,没有权限的内容不显示,而不是像现在这样显示所有的内容。

        这时候我们可以用到Securty-Thymeleaf整合包来实现这个效果:

第一步:在pom.xml文件中引入相应的整合包

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

        在html文件中导入springboot-security的命名空间:

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

第二步:我们在index中让他,如果登录了就显示注销按钮和登录的用户名,未登录就显示登录按钮

<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/gotologin}">登录</a>
</div>
<div sec:authorize="isAuthenticated()">
    用户名:<span sec:authentication="name"></span>
    角色:<span sec:authentication="principal.authorities"></span>
    <a th:href="@{/logout}">注销</a>
</div>

        如上所示用sec:authorize="!isAuthenticated()"来判断是否登录,登录了就显示用户信息和注销按钮,未登录就显示登录按钮

<div sec:authorize="hasRole('vip1')" id="level1" style="border: 1px solid black;float: left;width: 200px;text-align: center;margin-left: 450px;">
    <h3>level1</h3><br>
    <a th:href="@{/level1/1}">leval1-1html</a><br>
    <a th:href="@{/level1/2}">leval1-2html</a><br>
    <a th:href="@{/level1/3}">leval1-3html</a><br>
</div>

        如上所述的代码可以实现根据每个用户的权限来显示不同的内容

        sec:authorize="hasRole('vip1')"表示拥有vip1权限的用户可以看到该div的内容,其他两个div和这个写法类似,把vip1改成vip2、vip3即可,index页面代码如下所示

下面是index的完整代码:

<!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 style="text-align: center">
    <h1>首页</h1>
    <div sec:authorize="!isAuthenticated()">
        <a th:href="@{/gotologin}">登录</a>
    </div>

    <div sec:authorize="isAuthenticated()">
        用户名:<span sec:authentication="name"></span>
        角色:<span sec:authentication="principal.authorities"></span>
        <a th:href="@{/logout}">注销</a>
    </div>

</div>

<div sec:authorize="hasRole('vip1')" id="level1" style="border: 1px solid black;float: left;width: 200px;text-align: center;margin-left: 450px;">
    <h3>level1</h3><br>
    <a th:href="@{/level1/1}">leval1-1html</a><br>
    <a th:href="@{/level1/2}">leval1-2html</a><br>
    <a th:href="@{/level1/3}">leval1-3html</a><br>
</div>

<div sec:authorize="hasRole('vip2')" id="level2" style="border: 1px solid black;float: left;width: 200px;text-align: center;">
    <h3>level2</h3><br>
    <a th:href="@{/level2/1}">leval2-1html</a><br>
    <a th:href="@{/level2/2}">leval2-2html</a><br>
    <a th:href="@{/level2/3}">leval2-3html</a><br>
</div>

<div sec:authorize="hasRole('vip3')" id="level3" style="border: 1px solid black;float: left;width: 200px;text-align: center;">
    <h3>level3</h3><br>
    <a th:href="@{/level3/1}">leval3-1html</a><br>
    <a th:href="@{/level3/2}">leval3-2html</a><br>
    <a th:href="@{/level3/3}">leval3-3html</a><br>
</div>

</body>
</html>

27.0、记住我功能的开启以及login页面的自定义修改

        开启记住我功能只需要在配置类中加入:http.rememberMe();

实现原理其实就是一个cookie,他的默认有效期为两周时间

        我们再来将它默认的登录页面改为自己写的登录页面

在配置类中加入以下代码即可:

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

        这里注意:在我们登录的界面登录表单提交要以post方式提交,而且input用户名的name属性必须为username,密码input的name属性必须为password(这是因为源码中设置了默认值,不这么写就无法接收到参数,可以用usernameParamter()和passwordParamter()来修改默认值)。提交的action必须为/gotologin也就是和自己配置loginPage的url要一致,

        也可以用第二种方法:

        http.formLogin().loginPage("/gotologin").loginProcessingUrl("/login");

        这里loginPage表示默认登录的页面跳转的url,loginProcessingUrl表示登录提交的表单action必须要和这个login一致。

自己的登录界面如何开启记住我功能在下面的配置类代码里也写了。

配置类代码如下SecurityConfig.java:

package com.hkl.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@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();
        //注销,开启注销功能,并设置注销后跳转至index页面
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能
        http.rememberMe();
        //修改默认的登录页面
        http.formLogin().loginPage("/gotologin").loginProcessingUrl("/login");
        //开启自定义登录界面的记住我功能
        http.rememberMe().rememberMeParameter("remeber");
    }
    //认证,springboot2.1.x 可以直接使用~
    //密码加密编码处理:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多的加密的方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        这些认证的数据正常情况下应该从数据库里读取,但是由于我这里测试没有连接数据库,所以直接将数据写死。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("hkl").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("xiaolan").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    }
}

Login页面代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <style>
        #loginbtn {
            width: 210px;
            height: 35px;
            background-color: #428bca;
            border-color: #357ebd;
            color: #fff;
            border-radius: 10px; /* future proofing */
            text-align: center;
            border: 1px solid transparent;
            font-weight: bolder;
        }
        #username {
            font-family: 楷体;
            border-radius: 9px;
            width: 200px;
            height: 20px;
        }
        #password {
            font-family: 楷体;
            border-radius: 9px;
            width: 200px;
            height: 20px;
        }
    </style>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="border: 1px solid white;margin: 500px;margin-top: 200px;text-align: center;font-family: 楷体">
    <h3>登录</h3>
    <form th:action="@{/login}" method="post">
        <input id="username" type="text" name="username" placeholder="用户名" /><br><br>
        <input id="password" type="password" name="password" placeholder="密码" /><br><br>
        <input type="checkbox" name="remeber">记住我 <br>
        <input id="loginbtn" type="submit" value="登录" /><br><br>
    </form>
</div>
</body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值