【Spring Boot】Spring 的安全框架:Spring Security
    		       		warning:
    		            这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
    		        
        		                
                Spring Security是一个能够为基于Spring的企业应用系统提供强大安全性解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,实现了身份验证和授权功能,保护应用程序免受未授权的访问。
以下是一个简单的Spring Security配置示例,它使用内存中的用户和角色,并且没有使用数据库:
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(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}userPassword").roles("USER")
            .and()
            .withUser("admin").password("{noop}adminPassword").roles("USER", "ADMIN");
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/db/**").hasRole("USER")
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}在这个配置中,我们定义了两个用户:一个是普通用户user,另一个是管理员admin。我们还定义了几个URL模式的访问控制,例如/admin/**只对具有ADMIN角色的用户开放,/db/**只对具有USER角色的用户开放。登录页面设置为/login,所有用户都可以访问登录页面。
这只是一个简单的示例,实际应用中可能需要结合数据库等其他配置来实现更复杂的安全需求。
评论已关闭