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

SpringBoot 集成 SpringSecurity 详解(八)-- 退出登录和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值一致,<form action="/authentication/form" method="post">
                // 登录失败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页面,如下:

在这里插入图片描述

提示:

  1. 403.html 要放在resource/static/error 目录下;
  2. 记得配置参数failureUrl("/login/error")。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是 SpringBoot 集成 SpringSecurity 实现登录和权限管理的示例代码: 首先,我们需要在 pom.xml 中添加 SpringSecurity 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 然后,我们需要创建一个继承了 WebSecurityConfigurerAdapter 的配置类,并且使用 @EnableWebSecurity 注解启用 SpringSecurity: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在上面的代码中,我们通过 configure(AuthenticationManagerBuilder auth) 方法指定了使用哪个 UserDetailsService 来获取用户信息,通过 configure(HttpSecurity http) 方法配置了哪些 URL 需要哪些角色才能访问,以及登录页面和退出登录的 URL。 接下来,我们需要实现 UserDetailsService 接口,用来获取用户信息: ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities); } } ``` 在上面的代码中,我们通过 UserRepository 来获取用户信息,并且将用户的角色转换成 GrantedAuthority 对象。 最后,我们需要创建一个控制器来处理登录退出登录的请求: ```java @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { new SecurityContextLogoutHandler().logout(request, response, authentication); } return "redirect:/login?logout"; } } ``` 在上面的代码中,我们通过 @GetMapping 注解来处理登录退出登录的请求,并且在退出登录成功后重定向到登录页面。 以上就是 SpringBoot 集成 SpringSecurity 实现登录和权限管理的示例代码,希望对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值