【SpringBoot3】Spring Security 详细使用实例(简单使用、JWT模式)
import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance(); // 仅用于开发环境
}
}
这段代码定义了一个简单的Spring Security配置,它使用内存中的用户存储来认证用户,并为了简化起见,使用了不进行编码的NoOpPasswordEncoder
。在实际应用中,应该使用更安全的密码编码方式,如BCryptPasswordEncoder。同时,这个配置允许对"/", "/home"进行匿名访问,所有其他请求必须通过认证。这是一个典型的入门级配置,适合于快速开发和测试。
评论已关闭