csrf

时间:2017-06-04 18:06:32

标签: spring spring-security csrf freemarker

项目中必须使用Spring Security + Freemarker配置身份验证。我有登录页面

<#-- @ftlvariable name="_csrf" 
type="org.springframework.security.web.csrf.CsrfToken" -->
<#-- @ftlvariable name="error" type="java.util.Optional<String>" -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log in</title>
</head>
<body>
<nav role="navigation">
<ul>
    <li><a href="/">Home</a></li>
</ul>
</nav>
<h1>Log in</h1>
<p>You can use: demo@localhost / demo</p>
<form role="form" action="/login" method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div>
    <label for="email">Email address</label>
    <input type="email" name="email" id="email" required autofocus/>
</div>
<div>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" required/>
</div>
<div>
    <label for="remember-me">Remember me</label>
    <input type="checkbox" name="remember-me" id="remember-me"/>
</div>
<button type="submit">Sign in</button>
</form>
</body>
</html>

此页面由LoginController

处理
@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}

配置Spring Security

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = "projectpackages.janus")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;


protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/public/**").permitAll()
            .antMatchers("/users/**").hasAuthority("ADMINISTRATOR")
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email")
            .permitAll()
            .and()
            .logout().logoutUrl("/logout")
            .deleteCookies("remember-me")
            .logoutSuccessUrl("/")
            .permitAll()
            .and()
            .rememberMe();
}

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}

当我转到登录页面时,freemarker会抛出异常

FreeMarker template error:
The following has evaluated to null or missing:
==> _csrf  [in template "login.ftl" at line 21, column 34]

----
FTL stack trace ("~" means nesting-related):
- Failed at: ${_csrf.parameterName}  [in template "login.ftl" at line 21, 
column 32]
----

帮助了解此错误的可能原因。在互联网上搜索没有成功(

0 个答案:

没有答案