我如何在Spring Security中使用CSRF


问题内容

我的登录页面。

<form class="form-horizontal" ng-controller="loginCtrl" action="/login" method="post">
    <div class="form-group input-login">
        <div ng-if="message.error" class="alert alert-danger">
            <p>Invalid username and password.</p>
        </div>
        <div ng-if="message.logout" class="alert alert-success">
            <p>You have been logged out successfully.</p>
        </div>
        <label  class="control-label sr-only">Email</label>
        <div class="col-md-12">
            <input type="text" class="form-control" ng-model="user.username" name="username" placeholder="NickName"/>
        </div>
    </div>
    <div class="form-group input-login">
        <label  class="control-label sr-only">Password</label>
        <div class="col-md-12">
            <input type="password" class="form-control" ng-model="user.password" name="password" placeholder="Password"/>
        </div>
    </div>
    <input name="_csrf" type="hidden" value="6829b1ae-0a14-4920-aac4-5abbd7eeb9ee" /> 
    <div class="form-group sub-login">
        <div class=" col-md-12">
            <button name="submit" type="submit" class="btn btn-primary btn-login">Login</button>
        </div>
    </div>
</form>

但是,如果我没有禁用csrf,那就accessDenied总是。我不知道问题出在哪里。

我的配置代码如下。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDao userDao;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(new UserService(userDao)).passwordEncoder(new MD5Util());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/", "/index").access("hasRole('USER')")
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login#/signin?error=1")
                    .successHandler(new LoginSuccessHandler())
                    .usernameParameter("username").passwordParameter("password")
                .and()
                    .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/login#/signin?logout=1")
                .and()
                    .exceptionHandling().accessDeniedPage("/Access_Denied")
                .and().csrf().disable(); // If I  disable this csrf,it worked!

    }
}

而且没有人知道如何thymeleaf在其ng- route部分页面中使用。只看到这个问题


问题答案:

最好的选择是查看以下链接:https : //spring.io/blog/2015/01/12/the-login-page-
angular-js-and-spring-security-part-ii

特别地,相关部分是:

CSRF保护

很好,因为这意味着Spring Security内置的CSRF保护功能已开始发挥作用,以防止我们用脚射击。它所需要的只是在名为“
X-CSRF”的标头中发送给它的令牌。CSRF令牌的值是服务器端在加载主页的初始请求中的HttpRequest属性中可用的值。为了将其提供给客户端,我们可以使用服务器上的动态HTML页面来呈现它,或者通过自定义端点公开它,否则我们可以将其作为cookie发送。最后一个选择是最好的,因为Angular已基于cookie内置了对CSRF(称为“
XSRF”)的支持。

因此,我们在服务器上所需的只是一个自定义过滤器,该过滤器将发送cookie。Angular希望cookie名称为“ XSRF-TOKEN”,Spring
Security将其作为请求属性提供,因此我们只需要将值从请求属性转移到cookie:

public class CsrfHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        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);
    }
}

经过更多工作后,最后一句话是:

完成这些更改后,我们无需在客户端进行任何操作,并且登录表单现在可以使用了。