Spring Boot如何集成Spring Security?

在这里插入图片描述

🍅 作者简介:哪吒,CSDN2021博客之星亚军🏆、新星计划导师✌、博客专家💪

🍅 哪吒多年工作总结:Java学习路线总结,搬砖工逆袭Java架构师

🍅 技术交流:定期更新Java硬核干货,不定期送书活动

🍅 点击文末名片,关注公众号【哪吒编程】,回复 1024 ,获取《10万字208道Java经典面试题总结(附答案)》2024修订版pdf,背题更方便,一文在手,面试我有

嗨,你好呀,我是哪吒。

Spring Security 是一个功能强大且可高度定制的身份验证和访问控制框架。在 Spring Boot 应用中集成 Spring Security 可以提供安全的用户认证和授权机制。以下是集成 Spring Security 的基本步骤:

1、添加依赖

首先,在项目的 pom.xml(Maven)或 build.gradle(Gradle)文件中添加 Spring Security 的依赖。

对于 Maven:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- 其他依赖 -->
</dependencies>

对于 Gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    // 其他依赖
}

2、配置 Spring Security

创建一个配置类,继承 WebSecurityConfigurerAdapter 并重写相应的方法来定义安全策略。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()  // 允许所有用户访问首页
                .anyRequest().authenticated()    // 其他所有请求需要认证
                .and()
            .formLogin()
                .loginPage("/login")            // 定制登录页
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
    
    // 可以添加更多的安全配置
}

3、创建登录页

Spring Security 会根据 configure(HttpSecurity http) 方法中定义的 loginPage 路径来寻找登录页。你可以创建一个自定义的登录页,或者使用 Spring Boot 默认提供的登录页。

4、用户认证

Spring Security 支持多种用户认证方式,包括内存数据库、JDBC 数据库、LDAP 等。以下是使用内存数据库进行用户认证的示例:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
            .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
            .and()
            .withUser("admin").password(passwordEncoder().encode("admin")).roles("USER", "ADMIN");
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

5、启动类

确保你的 Spring Boot 启动类上有 @SpringBootApplication 注解,这样 Spring Boot 才能自动扫描并加载配置。

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

6、自定义安全配置

根据需要,你可以添加更多的安全配置,如密码策略、记住我功能、CORS 过滤器、自定义权限验证等。

7、测试

启动应用并访问受保护的资源,以确保安全配置按预期工作。

通过以上步骤,你可以在 Spring Boot 应用中集成 Spring Security,实现用户认证和授权。Spring Security 提供了灵活的扩展点,允许你根据应用的具体需求定制安全策略。


🏆文章收录于:Spring Boot 进阶实战

哪吒数年工作总结之结晶。

🏆哪吒多年工作总结:Java学习路线总结,搬砖工逆袭Java架构师

2024华为OD统一考试题库清单(持续收录中)以及考点说明点这里

刷的越多,抽中的概率越大,每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天CSDN在线答疑。

点击下方名片,回复1024,获取《10万字208道Java经典面试题总结(2024修订版).pdf 》

在这里插入图片描述

  • 21
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Spring Boot项目中集成Spring Security非常简单,只需要在项目中增加Spring Boot Security的依赖即可。下面是一个基础的Spring Boot Security登录验证的示例: 1.在pom.xml文件中添加Spring Boot Security依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2.创建一个WebSecurityConfig类,用于配置Spring Security: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } ``` 3.在上面的代码中,我们配置了一个基本的登录验证,只有经过身份验证的用户才能访问应用程序的其他部分。我们还定义了一个用户“user”,密码为“password”,并将其分配给“USER”角色。 4.在应用程序中,我们还需要一个登录页面。在templates文件夹中创建一个名为“login.html”的文件,添加以下内容: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Login</title> </head> <body> <h1>Login</h1> <form th:action="@{/login}" method="post"> <div><label>Username: <input type="text" name="username" /></label></div> <div><label>Password: <input type="password" name="password" /></label></div> <<div><input type="submit" value="Sign In" /></div> </form> </body> </html> ``` 5.最后,在应用程序的控制器中添加一个映射到登录页面的请求处理程序: ```java @Controller public class HomeController { @RequestMapping(value = {"/", "/home"}) public String home() { return "home"; } @RequestMapping(value = "/login") public String login() { return "login"; } } ``` 这样,我们就完成了一个基本的Spring Boot Security登录验证的配置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哪 吒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值