參考鏈接:https://segmentfault.com/q/1010000012743613
有兩個controller,一個是所有用戶可以訪問的@RequestMapping("user"),
還有一個是管理員可以訪問的@RequestMapping("admin")。
/user/login是UserController中的登錄url。
所有操作(除登錄注銷)都要登錄之后才能進行。
現在想用springboot結合spring security實現權限管理。
系統是前后端分離的,controller中返回數據,不返回頁面,WebMvcConfig也沒有配置什么。
但/user/login,post怎么也不通。報403錯誤。
這是錯誤信息
這是WebSecurityConfig
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean UserDetailsService customUserService() { //注冊UserDetailsService 的bean return new CustomUserService(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/**").access("hasRole('ROLE_USER')") .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") .anyRequest().authenticated().and() // access after login // .rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("").and() .formLogin().loginProcessingUrl("user/login").permitAll().and() .logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService()); } }
這是CustomUserService
@Service public class CustomUserService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { System.out.println("loadUser " + s); User user = userService.getUserByUsername(s); if (user == null || user.getIsDel() == 1) { throw new UsernameNotFoundException("user not exist"); } List<GrantedAuthority> auths = new ArrayList<>(); for (Role role : user.getRoles()) { auths.add(new SimpleGrantedAuthority(role.getName())); //不同用戶會返回不同的role.name:ROLE_USER, ROLE_ADMIN } return new org.springframework.security.core.userdetails.User(s , user.getPwd(), auths); } }
最后即使我在WebSecurity中什么也不配置,默認應該是不需要驗證session吧。
仍然不行。
protected void configure(HttpSecurity http) throws Exception { }
問題原因及解決方案:
看錯誤提示,可能是因為你開啟了CSRF保護,關閉即可,在configure(HttpSecurity http)
方法中追加http.csrf().disable();