1. 程式人生 > >Spring Boot整合Spring Security

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