【发布时间】:2016-01-18 16:22:22
【问题描述】:
我有一个带有 thymeleaf 模板的 Spring Boot 应用程序,并使用带有 AngularJS 的 HTML 作为我的前端,使用 mysql 作为 DATABASE,数据以 JSON 形式传递
<!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?
-
Java代码没有jsp!
-
确认弹窗来自浏览器,所以有客户端。什么是客户?简单的html、js还是一些框架?
-
我正在尝试访问一个 Html 文件,并且出现了一个确认弹出窗口以进行身份验证!当我删除它时,身份验证不会到来,所以它必须来自 spring 框架
org.springframework.boot spring-boot-starter-security
标签: javascript html spring spring-boot