Spring Boot-搭建SpringSecurity(保姆级别)
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个使用Spring Security和Spring Boot的简单示例,它提供了基本的安全性设置,仅用于演示目的。
- 首先,在pom.xml中添加Spring Security依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>- 创建一个安全配置类,继承WebSecurityConfigurerAdapter:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}在这个配置中,我们定义了一个用户user和密码password,并且用{noop}前缀是为了告诉Spring Security不要加密密码。在实际应用中,你应该使用加密的密码和更安全的用户存储方式。
- 运行你的Spring Boot应用,并尝试访问应用中的端点。你将被重定向到登录页面,需要输入刚才定义的用户凭证来访问。
这个示例展示了如何在Spring Boot应用中设置Spring Security的基本配置,并且提供了一个简单的登录认证。在实际应用中,你需要根据自己的需求进行更复杂的配置,比如使用数据库来存储用户信息,或者集成其他的认证提供者等。
评论已关闭