创建一个简单的 Spring Security 项目

本文介绍了如何创建一个简单的Spring Security项目。通过Spring Initializr添加Security和Web依赖,然后声明访问URL。项目运行后,Spring Security默认启用HTTP基本认证,需要用户名user和控制台生成的密码进行登录。虽然基本认证不常用,但可以自定义实现表单认证以提高安全性。
摘要由CSDN通过智能技术生成

1.新建spring boot项目

 

2. 选择依赖项

Spring Initializr 允许我们提前选定一些常用的项目依赖,此处我们选择 Security 作为构建 Spring Security 项目的最小依赖,选择 Web 作为 Spring Boot 构建 Web 应用的核心依赖。 

 

打开 pom.xml 文件,看看 Spring Initializr 引入了哪些依赖。

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单Spring Boot 整合 Spring Security 6 的项目示例: 首先,需要在 pom.xml 文件中添加相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <version>6.0.1</version> <scope>test</scope> </dependency> ``` 然后,在 Spring Boot 的 Application 类上添加 `@EnableWebSecurity` 注解: ```java @SpringBootApplication @EnableWebSecurity public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 接下来,创建一个类继承 `WebSecurityConfigurerAdapter` 并重写 `configure(HttpSecurity http)` 方法来配置安全规则: ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("{noop}password") .roles("USER"); } } ``` 在上面的代码中,我们配置了 `/login` 路径为公开访问,其他路径需要进行身份验证。同时,我们设置了一个基于内存的用户存储并指定了一个用户名和密码。 最后,创建一个简单的登录页面: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h2>Login</h2> <form method="post" action="/login"> <label for="username">Username:</label> <input type="text" id="username" name="username" /><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" /><br><br> <button type="submit">Login</button> </form> </body> </html> ``` 以上就是一个简单Spring Boot 整合 Spring Security 6 的项目示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值