Spring Boot整合Spring Security

只開啓了簡單的登陸驗證

添加依賴

 <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();
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章