鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ springboot中使用spring security,登錄url就出現(xiàn)403

springboot中使用spring security,登錄url就出現(xiàn)403錯誤

有兩個controller,一個是所有用戶可以訪問的@RequestMapping("user"),
還有一個是管理員可以訪問的@RequestMapping("admin")。

/user/login是UserController中的登錄url。
所有操作(除登錄注銷)都要登錄之后才能進行。

現(xiàn)在想用springboot結(jié)合spring security實現(xiàn)權(quán)限管理。
系統(tǒng)是前后端分離的,controller中返回數(shù)據(jù),不返回頁面,WebMvcConfig也沒有配置什么。

但/user/login,post怎么也不通。報403錯誤。

這是錯誤信息

clipboard.png

{"timestamp":1515379466882,"status":403,"error":"Forbidden","message":"Could not verify the provided CSRF token because your session was not found.","path":"/email/user/login"}

這是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中什么也不配置,默認(rèn)應(yīng)該是不需要驗證session吧。
仍然不行。

protected void configure(HttpSecurity http) throws Exception {
}
回答
編輯回答
雨蝶

關(guān)掉csrf并不是建議的做法,因為安全原因

建議按spring的文件加上相應(yīng)的token就好

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

參考鏈接:
https://stackoverflow.com/que...

https://docs.spring.io/spring...

2018年4月24日 06:50
編輯回答
逗婦乳

看錯誤提示,可能是因為你開啟了CSRF保護,關(guān)閉即可,在configure(HttpSecurity http)方法中追加http.csrf().disable();

2017年12月11日 03:23