欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot整合Spring Security

程序员文章站 2022-03-02 14:38:07
...

只开启了简单的登陆验证

添加依赖

 <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();
 }
}
相关标签: springboot