Spring Boot整合Spring Security

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stSahana/article/details/83622896

只开启了简单的登陆验证

添加依赖

 <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();
 }
}

猜你喜欢

转载自blog.csdn.net/stSahana/article/details/83622896