SpringBoot 集成 SpringSecurity 详解(八)-- 退出登录和403异常处理

SpringBoot 集成 SpringSecurity 详解(八)-- 退出登录和403异常处理

  • 需求缘起
  • 技术要点
  • 一、退出登录
  • 二、403异常处理

需求缘起

既然有了登录就应该有登出,这一节我们来实现登出功能;
我们访问接口 http://localhost:8080/hello/helloAdmin,如果我们用账户"user"登录,我们会发现报了403异常,而且界面很不友好,这一节我们来实现自定义403界面。

本节是在第七小节的基础上继续开发。

本节 demo

技术要点

  1. 编写登出界面
  2. 编写403界面
  3. 相关配置

一、退出登录

1.1 编辑界面
退出登录特别的简单,这个Spring Security就已经帮我们实现了,只需要在login.html使用form表单post方式,提交/logout请求即可,如下示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/authentication/form" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
<form action="/logout" method="post">
    <table>
        <tr>
            <td colspan="2">
                <button type="submit">退出登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

1.2 配置
配置 logout().permitAll();完整代码请继续往下看。

1.3 测试
重启应用,访问http://localhost:8080/hello/helloAdmin,输入用户名"admin"和密码"123456";
再访问 http://localhost:8080/login.html,点击退出登录,然后再 http://localhost:8080/hello/helloAdmin,如果跳转到登录界面说明退出登录功能已做好。

二、403异常处理

2.1 编写403界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>403页面</title>
</head>
<body>
<h2>403:你没有权限访问此页面</h2>
</body>
</html>

2.2 配置
// 登录失败Url
.failureUrl("/login/error")
完整配置代码

@Configuration
@EnableWebSecurity//开启Spring Security的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法安全级别的控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        //SpringSecurity 提供的一种编码器,我们也可以自己实现PasswordEncoder
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()
                .loginPage("/login.html")// 自定义登录页面路径
                .loginProcessingUrl("/authentication/form")// 自定义页面的登录路径,注意要与登录页面的action值一致,
// 登录失败Url .failureUrl("/login/error") .and() .logout().permitAll() .and() .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护 .antMatchers("/login.html").permitAll()// 设置所有人都可以访问登录页面 .anyRequest().authenticated() // 除了以上的请求外都需要身份验证 ; http.csrf().disable();// 禁用跨站攻击 } }

2.3 测试
重启应用,访问http://localhost:8080/hello/helloAdmin,输入用户名"user"和密码"123456";因为没有权限访问这个方法,跳转到自定义的403页面,如下:

SpringBoot 集成 SpringSecurity 详解(八)-- 退出登录和403异常处理_第1张图片

提示:

  1. 403.html 要放在resource/static/error 目录下;
  2. 记得配置参数failureUrl("/login/error")。

你可能感兴趣的:(SpringSecurity,入门到精通)