Search in sources :

Example 26 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project hub-alert by blackducksoftware.

the class HomeController method checkAuthentication.

@GetMapping(value = "/api/verify")
public ResponseEntity<String> checkAuthentication(final HttpServletRequest request) {
    final HttpServletRequest httpRequest = request;
    final CsrfToken csrfToken = csrfTokenRespository.loadToken(request);
    if (csrfToken == null) {
        httpRequest.getSession().invalidate();
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    } else {
        final String body = "{\"message\":\"Authenticated\"}";
        final HttpHeaders headers = new HttpHeaders();
        headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) CsrfToken(org.springframework.security.web.csrf.CsrfToken) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 27 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project cloud-sea-towerman by huadahuang1983.

the class WebSecurityConfig method csrfHeaderFilter.

private Filter csrfHeaderFilter() {
    return new 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 = new Cookie("XSRF-TOKEN", csrf.getToken());
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            filterChain.doFilter(request, response);
        }
    };
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) OncePerRequestFilter(org.springframework.web.filter.OncePerRequestFilter) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) CsrfToken(org.springframework.security.web.csrf.CsrfToken)

Example 28 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project spring-security by spring-projects.

the class WebSocketMessageBrokerConfigTests method requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor.

@Test
public void requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor() throws Exception {
    this.spring.configLocations(xml("SyncSockJsConfig")).autowire();
    WebApplicationContext context = this.spring.getContext();
    MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
    String csrfAttributeName = CsrfToken.class.getName();
    String customAttributeName = this.getClass().getName();
    MvcResult result = mvc.perform(get("/app/289/tpyx6mde/websocket").requestAttr(csrfAttributeName, this.token).sessionAttr(customAttributeName, "attributeValue")).andReturn();
    CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName);
    String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName);
    String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName);
    assertThat(handshakeToken).isEqualTo(this.token).withFailMessage("CsrfToken is populated");
    assertThat(handshakeValue).isEqualTo(sessionValue).withFailMessage("Explicitly listed session variables are not overridden");
}
Also used : MvcResult(org.springframework.test.web.servlet.MvcResult) DefaultCsrfToken(org.springframework.security.web.csrf.DefaultCsrfToken) CsrfToken(org.springframework.security.web.csrf.CsrfToken) MockMvc(org.springframework.test.web.servlet.MockMvc) WebApplicationContext(org.springframework.web.context.WebApplicationContext) Test(org.junit.jupiter.api.Test)

Example 29 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project spring-security by spring-projects.

the class SessionManagementConfigurerServlet31Tests method changeSessionIdThenPreserveParameters.

@Test
public void changeSessionIdThenPreserveParameters() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
    String id = request.getSession().getId();
    request.getSession();
    request.setServletPath("/login");
    request.setMethod("POST");
    request.setParameter("username", "user");
    request.setParameter("password", "password");
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    CsrfToken token = repository.generateToken(request);
    repository.saveToken(token, request, this.response);
    request.setParameter(token.getParameterName(), token.getToken());
    request.getSession().setAttribute("attribute1", "value1");
    loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
    this.springSecurityFilterChain.doFilter(request, this.response, this.chain);
    assertThat(request.getSession().getId()).isNotEqualTo(id);
    assertThat(request.getSession().getAttribute("attribute1")).isEqualTo("value1");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpSessionCsrfTokenRepository(org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository) CsrfToken(org.springframework.security.web.csrf.CsrfToken) Test(org.junit.jupiter.api.Test)

Example 30 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project spring-security by spring-projects.

the class DefaultFiltersTests method defaultFiltersPermitAll.

@Test
public void defaultFiltersPermitAll() throws IOException, ServletException {
    this.spring.register(DefaultFiltersConfigPermitAll.class, UserDetailsServiceConfig.class);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
    request.setServletPath("/logout");
    CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
    new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response);
    request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
    this.spring.getContext().getBean("springSecurityFilterChain", Filter.class).doFilter(request, response, new MockFilterChain());
    assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");
}
Also used : SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Filter(jakarta.servlet.Filter) SessionManagementFilter(org.springframework.security.web.session.SessionManagementFilter) LogoutFilter(org.springframework.security.web.authentication.logout.LogoutFilter) AnonymousAuthenticationFilter(org.springframework.security.web.authentication.AnonymousAuthenticationFilter) CsrfFilter(org.springframework.security.web.csrf.CsrfFilter) SecurityContextHolderAwareRequestFilter(org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter) ExceptionTranslationFilter(org.springframework.security.web.access.ExceptionTranslationFilter) RequestCacheAwareFilter(org.springframework.security.web.savedrequest.RequestCacheAwareFilter) UsernamePasswordAuthenticationFilter(org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter) HeaderWriterFilter(org.springframework.security.web.header.HeaderWriterFilter) WebAsyncManagerIntegrationFilter(org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DefaultCsrfToken(org.springframework.security.web.csrf.DefaultCsrfToken) MockFilterChain(org.springframework.mock.web.MockFilterChain) DefaultCsrfToken(org.springframework.security.web.csrf.DefaultCsrfToken) CsrfToken(org.springframework.security.web.csrf.CsrfToken) HttpSessionCsrfTokenRepository(org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

CsrfToken (org.springframework.security.web.csrf.CsrfToken)48 Test (org.junit.jupiter.api.Test)28 DefaultCsrfToken (org.springframework.security.web.csrf.DefaultCsrfToken)17 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 HttpSessionCsrfTokenRepository (org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository)8 Authentication (org.springframework.security.core.Authentication)6 Cookie (javax.servlet.http.Cookie)5 HashMap (java.util.HashMap)3 ServletContext (javax.servlet.ServletContext)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)3 ActionResponse (com.synopsys.integration.alert.common.action.ActionResponse)2 FilterChain (javax.servlet.FilterChain)2 HttpHeaders (org.springframework.http.HttpHeaders)2 MockFilterChain (org.springframework.mock.web.MockFilterChain)2 MockHttpSession (org.springframework.mock.web.MockHttpSession)2