SpringBoot 集成 SpringSecurity 的基本使用

主要依赖

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

在配置文件里配置账号,密码(也可以在自定义配置类里配置)

application.properties

# 自定义用户名
spring.security.user.name=admin
# 自定义密码
spring.security.user.password=admin

自定义配置

@Configuration
@EnableWebSecurity
public class MyConfigSecurity extends WebSecurityConfigurerAdapter {

    // 加密方式
    private final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 基于内存存储的多用户
        auth.inMemoryAuthentication().withUser("root").password(ENCODER.encode("root")).roles("root").and()
                .withUser("admin").password(ENCODER.encode("admin")).roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略静态请求
        web.ignoring().antMatchers("/img/**", "/js/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 不需要验证的请求
                .antMatchers("/swagger").permitAll()
                // 所有请求都需要验证
                .anyRequest().authenticated()
                .and()
                // 登录页面
                .formLogin().loginPage("/in.html")
                // 登录信息请求路径
                .loginProcessingUrl("/login")
                // 登录成功跳转的路径
                .defaultSuccessUrl("/")
                // 登录成功后的回调
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        Authentication authentication) throws IOException, ServletException {
                        System.out.println(authentication.getName() + "登录成功");
                    }
                })
                // 登录失败跳转的路径
                .failureUrl("/login.html?error")
                // 登录失败后的回调
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        AuthenticationException exception) throws IOException, ServletException {
                        exception.printStackTrace();
                    }
                })
                //permitAll 给没登录的 用户可以访问这个地址的权限
                .permitAll()
                .and()
                // 登出后跳转路径
                .logout().logoutUrl("/out")
                // 登出后的回调
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request,
                                       HttpServletResponse response,
                                       Authentication authentication) {
                        System.out.println(authentication.getName() + "退出登录");
                    }
                })
                .and()
                .csrf()
                //关闭csrf防护
                .disable()
                // 记住我(与踢掉登录用户冲突)
                .rememberMe().and()
                // 踢掉其他已登录的用户(与记住我冲突)
                //.sessionManagement()
                // 最多只能有1个用户登录
                //.maximumSessions(1)
                //禁止其他终端登录
                //.maxSessionsPreventsLogin(true)
                ;
    }

    /**
     * 
     * @return 返回加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return ENCODER;
    }

    /**
     * 及时清理过期session
     *
     * @return
     */
    @Bean
    HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

}

in.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<!-- action = 登录信息请求路径 -->
<form action="/login" method="post">
    <label for="username">账号</label><input id="username" type="text" name="username"><br>
    <label for="password">密码</label><input id="password" type="password" name="password"><br>
    <p><input type='checkbox' name='remember-me'/> 记住我 </p>
    <input type="submit" value="登录"/>
</form>

</body>
</html>
posted @   叕叕666  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示