Spring Boot与Spring Security结合MyBatis构建安全的RESTful Web服务
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}user").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
这段代码定义了一个基本的Spring Security配置,它使用内存中的用户存储来认证用户,并配置了HTTP安全性。它禁用了CSRF保护,允许对H2数据库控制台的访问,并且要求所有其他请求都需要认证。同时,它启用了基本认证。这个配置是一个简化的例子,用于演示如何将Spring Security集成到Spring Boot应用中。
评论已关闭