Spring Boot整合Spring Security

本文介绍如何在Spring Boot项目中使用Spring Security进行简单的登录验证配置。通过添加依赖、实现MyUserDetailService来加载用户详细信息,以及配置WebSecurityConfig以自定义登录页面和权限控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

只开启了简单的登陆验证

添加依赖

 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
 </dependency>

MyUserDetailService

 @Override @Primary public UserDetails loadUserByUsername(String s)
     throws UsernameNotFoundException {
   User user = userMapper.selectByPrimaryKey(s);
   if (user != null) {
     List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
     grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole()));
     return new org.springframework.security.core.userdetails.User(user.getUsername(),
         user.getPassword(), grantedAuthorities);
   } else {
     throw new UsernameNotFoundException("user<" + s + ">do not exist!");
   }
 }

WebSecurityConfig

@Configuration @EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)  //  启用方法级别的权限认证
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 @Autowired private MyUserDetailService myUserDetailService;

 @Override protected void configure(HttpSecurity http) throws Exception {
   //super.configure(http);
   http.csrf().disable();
   http.headers().frameOptions().disable();//允许使用frame

   http.authorizeRequests().antMatchers("/css/**", "/js/**", "/img/**", "/cdn/**", "/diploma/**")
       .permitAll().anyRequest().authenticated().and().formLogin()
       .loginPage("/login")// 登录url请求路径 (3)
       .defaultSuccessUrl("/").permitAll().and() // 登录成功跳转路径url(4)
       .logout().permitAll();
   //    http.logout().logoutSuccessUrl("/"); // 退出默认跳转页面 (5)
 }

 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
 }

 @Bean public PasswordEncoder passwordEncoder() {
   return new BCryptPasswordEncoder();
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值