SpringBoot 整合 Spring Security 、JWT 实现认证、权限控制
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 配置用户详情服务
auth.userDetailsService(userDetailsService());
}
@Bean
public PasswordEncoder passwordEncoder() {
// 使用BCrypt强散列方式
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public UserDetailsService userDetailsService() {
// 创建自定义的UserDetailsService实现
return new CustomUserDetailsService();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 配置路径的权限控制
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll() // 允许访问H2数据库控制台
.antMatchers("/auth/login").permitAll() // 允许登录接口免登录验证
.anyRequest().authenticated() // 其他所有请求需要身份验证
.and()
.csrf().disable() // 禁用CSRF保护
.exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint());
// 应用JWT
http
.addFilterBefore(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), tokenProvider),
UsernamePasswordAuthenticationFilter.class);
}
}
这个代码实例展示了
评论已关闭