我有thymeleaf模板春季啓動應用程序,並使用HTML與AngularJS作爲我與MySQL作爲數據庫和數據在JSON帶應用程序認證的Spring Boot(403 Fobidden)CSRF令牌爲空。你的會話過期了嗎?
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>
我的JS文件傳遞前端,其價值被髮布到:
$scope.logincheck = function() {
var dataObj = {
userId : $scope.userId,
password : $scope.password
};
var res = $http.post('http://localhost:9393/company/login', dataObj);
和相應的控制器,它處理的MySQL認證:
@RequestMapping(value = "/company/login", method = RequestMethod.POST)
如果啓用CSRF沒有得到調用。在CSRF啓用後,我得到403錯誤,說明發現CSRF標記爲空。
我webconfig.java:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/", "/login").permitAll()
.antMatchers("/hello").access("hasRole('ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/accessdenied")
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository());
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMIN")
}
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
public class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("Inside Webappconfig.java");
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
您的客戶是什麼?只是普通的js客戶端或jsp? – Aviad
Java代碼沒有jsp! – Vikram
確認彈出窗口來自瀏覽器,所以有客戶端。什麼是客戶?簡單的HTML,JS或一些框架? – Aviad