如何在spring security中使用过滤器并在过滤器中开发身份验证

时间:2016-06-28 13:47:34

标签: java spring spring-mvc spring-security

我使用Spring安全性开发了一个应用程序,并根据admin和customer等用户角色登录,我发现它已登录app / j_spring_security_check。我想实现具有安全性和身份验证的过滤器并跟踪所有网址。请说明实施方式

1 个答案:

答案 0 :(得分:2)

Security_configuration.java

  @Configuration
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Autowired
        CustomUserDetailsService userDetailsService;


        @Autowired
        DataSource datasource;
        Logger logger = LoggerFactory.getLogger(getClass());

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

            http.httpBasic().and().authorizeRequests().antMatchers("/public/**")
                    .permitAll().antMatchers("/admin/**").hasAuthority("admin")
                    .antMatchers("/user/**").hasAuthority("user")
                    .and()
                    .logout()
                    // Logout requires form submit. Bypassing the same.
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/index.html").and()
                    .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                    .csrf().
                                      requireCsrfProtectionMatcher(new
                                      CsrfRequestMatcher())
                                      .csrfTokenRepository(csrfTokenRepository());


        }
    }

csrfheaderfilter.java

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

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, "CSRF-TOKEN");
            String token = csrf.getToken();
            if (cookie == null || token != null
                    && !token.equals(cookie.getValue())) {
                cookie = new Cookie("CSRF-CSRF-TOKEN", token);
                cookie.setPath("/main.html");
                cookie.setHttpOnly(true);
                cookie.setMaxAge(20);
                response.addCookie(cookie);

            }
        }
        filterChain.doFilter(request, response);
    }
}

csrfrequestmatcher.java

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 
 * The default functionality is to skip CSRF checking for GET method. This
 * functionality is lost when an explicit request matcher is provided. So, need
 * to make sure that GET methods are skipped manually.
 *
 */

public class CsrfRequestMatcher implements RequestMatcher {

    // Always allow the HTTP GET method
    private Pattern allowedMethods = Pattern.compile("^GET$");
    private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher(
            "/unprotected", null);

    @Override
    public boolean matches(HttpServletRequest request) {

        // Skip checking if request method is a GET
        if (allowedMethods.matcher(request.getMethod()).matches()) {
            return false;
        }

        // Check CSRF in all other cases.
        return !unprotectedMatcher.matches(request);
    }

}