Search in sources :

Example 36 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project midpoint by Evolveum.

the class MidPointApplication method init.

@Override
public void init() {
    super.init();
    getCspSettings().blocking().disabled();
    getJavaScriptLibrarySettings().setJQueryReference(new PackageResourceReference(MidPointApplication.class, // todo no jquery.js is found
    "../../../../../webjars/AdminLTE/2.4.18/bower_components/jquery/dist/jquery.min.js"));
    getComponentInstantiationListeners().add(new SpringComponentInjector(this, applicationContext, true));
    systemConfigurationChangeDispatcher.registerListener(new DeploymentInformationChangeListener(this));
    SystemConfigurationType config = getSystemConfigurationIfAvailable();
    if (config != null) {
        deploymentInfo = config.getDeploymentInformation();
    }
    ResourceSettings resourceSettings = getResourceSettings();
    resourceSettings.setParentFolderPlaceholder("$-$");
    resourceSettings.setHeaderItemComparator(new PriorityFirstComparator(true));
    SecurePackageResourceGuard guard = (SecurePackageResourceGuard) resourceSettings.getPackageResourceGuard();
    guard.addPattern("+*.woff2");
    List<IStringResourceLoader> resourceLoaders = resourceSettings.getStringResourceLoaders();
    resourceLoaders.add(0, new MidPointStringResourceLoader(localizationService));
    IResourceStreamLocator locator = new CachingResourceStreamLocator(new MidPointResourceStreamLocator(resourceSettings.getResourceFinders()));
    resourceSettings.setResourceStreamLocator(locator);
    resourceSettings.setThrowExceptionOnMissingResource(false);
    getMarkupSettings().setStripWicketTags(true);
    getMarkupSettings().setStripComments(true);
    if (RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType())) {
        getDebugSettings().setAjaxDebugModeEnabled(true);
        getDebugSettings().setDevelopmentUtilitiesEnabled(true);
        initializeDevelopmentSerializers();
        mount(new MountedMapper("/inspector", InspectorPage.class, new PageParametersEncoder()));
        mount(new MountedMapper("/liveSession", LiveSessionsPage.class, new PageParametersEncoder()));
        mount(new MountedMapper("/pageStore", PageStorePage.class, new PageParametersEncoder()));
    }
    // pretty url for resources (e.g. images)
    mountFiles(ImgResources.BASE_PATH, ImgResources.class);
    // exception handling an error pages
    ApplicationSettings appSettings = getApplicationSettings();
    appSettings.setAccessDeniedPage(PageError401.class);
    appSettings.setInternalErrorPage(PageError.class);
    appSettings.setPageExpiredErrorPage(PageError.class);
    mount(new MountedMapper(MOUNT_INTERNAL_SERVER_ERROR, PageError.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_UNAUTHORIZED_ERROR, PageError401.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_FORBIDEN_ERROR, PageError403.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_NOT_FOUND_ERROR, PageError404.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_GONE_ERROR, PageError410.class, new PageParametersEncoder()));
    getRequestCycleListeners().add(new LoggingRequestCycleListener(this));
    getAjaxRequestTargetListeners().add(new AjaxRequestTarget.IListener() {

        @Override
        public void updateAjaxAttributes(AbstractDefaultAjaxBehavior behavior, AjaxRequestAttributes attributes) {
            // check whether behavior will use POST method, if not then don't put CSRF token there
            if (!isPostMethodTypeBehavior(behavior, attributes)) {
                return;
            }
            CsrfToken csrfToken = SecurityUtils.getCsrfToken();
            if (csrfToken == null) {
                return;
            }
            String parameterName = csrfToken.getParameterName();
            String value = csrfToken.getToken();
            attributes.getExtraParameters().put(parameterName, value);
        }
    });
    getSessionListeners().add((ISessionListener) asyncWebProcessManager);
    // descriptor loader, used for customization
    new PageMounter().loadData(this);
    descriptorLoader.loadData();
    if (applicationContext != null) {
        Map<String, MidPointApplicationConfiguration> map = applicationContext.getBeansOfType(MidPointApplicationConfiguration.class);
        if (map != null) {
            map.forEach((key, value) -> value.init(this));
        }
    }
    // for schrodinger selenide library
    initializeSchrodinger();
    ServletContext servletContext = getServletContext();
    if (servletContext != null) {
        taskManager.setWebContextPath(servletContext.getContextPath());
    }
}
Also used : CachingResourceStreamLocator(org.apache.wicket.core.util.resource.locator.caching.CachingResourceStreamLocator) MountedMapper(org.apache.wicket.core.request.mapper.MountedMapper) MidPointResourceStreamLocator(com.evolveum.midpoint.web.util.MidPointResourceStreamLocator) IResourceStreamLocator(org.apache.wicket.core.util.resource.locator.IResourceStreamLocator) InspectorPage(org.apache.wicket.devutils.inspector.InspectorPage) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) PriorityFirstComparator(org.apache.wicket.markup.head.PriorityFirstComparator) MidPointStringResourceLoader(com.evolveum.midpoint.web.util.MidPointStringResourceLoader) AbstractDefaultAjaxBehavior(org.apache.wicket.ajax.AbstractDefaultAjaxBehavior) PackageResourceReference(org.apache.wicket.request.resource.PackageResourceReference) IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader) ServletContext(javax.servlet.ServletContext) LiveSessionsPage(org.apache.wicket.devutils.inspector.LiveSessionsPage) MidPointApplicationConfiguration(com.evolveum.midpoint.gui.api.util.MidPointApplicationConfiguration) PageStorePage(org.apache.wicket.devutils.pagestore.PageStorePage) CsrfToken(org.springframework.security.web.csrf.CsrfToken) PageMounter(com.evolveum.midpoint.web.application.PageMounter) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) AjaxRequestAttributes(org.apache.wicket.ajax.attributes.AjaxRequestAttributes) ApplicationSettings(org.apache.wicket.settings.ApplicationSettings) SecurePackageResourceGuard(org.apache.wicket.markup.html.SecurePackageResourceGuard) ResourceSettings(org.apache.wicket.settings.ResourceSettings) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) PageParametersEncoder(org.apache.wicket.request.mapper.parameter.PageParametersEncoder) SpringComponentInjector(org.apache.wicket.spring.injection.annot.SpringComponentInjector)

Example 37 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project midpoint by Evolveum.

the class SecurityUtils method getCsrfToken.

public static CsrfToken getCsrfToken() {
    Request req = RequestCycle.get().getRequest();
    HttpServletRequest httpReq = (HttpServletRequest) req.getContainerRequest();
    return (CsrfToken) httpReq.getAttribute("_csrf");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.apache.wicket.request.Request) CsrfToken(org.springframework.security.web.csrf.CsrfToken)

Example 38 with CsrfToken

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

the class CsrfChannelInterceptor method preSend.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    if (!this.matcher.matches(message)) {
        return message;
    }
    Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders());
    CsrfToken expectedToken = (sessionAttributes != null) ? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null;
    if (expectedToken == null) {
        throw new MissingCsrfTokenException(null);
    }
    String actualTokenValue = SimpMessageHeaderAccessor.wrap(message).getFirstNativeHeader(expectedToken.getHeaderName());
    boolean csrfCheckPassed = expectedToken.getToken().equals(actualTokenValue);
    if (!csrfCheckPassed) {
        throw new InvalidCsrfTokenException(expectedToken, actualTokenValue);
    }
    return message;
}
Also used : MissingCsrfTokenException(org.springframework.security.web.csrf.MissingCsrfTokenException) CsrfToken(org.springframework.security.web.csrf.CsrfToken) InvalidCsrfTokenException(org.springframework.security.web.csrf.InvalidCsrfTokenException)

Example 39 with CsrfToken

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

the class SecurityMockMvcRequestPostProcessorsCsrfTests method csrfWhenUsedThenDoesNotImpactOriginalRepository.

// gh-4016
@Test
public void csrfWhenUsedThenDoesNotImpactOriginalRepository() throws Exception {
    // @formatter:off
    this.mockMvc.perform(post("/").with(csrf()));
    MockHttpServletRequest request = new MockHttpServletRequest();
    HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
    CsrfToken token = repo.generateToken(request);
    repo.saveToken(token, request, new MockHttpServletResponse());
    MockHttpServletRequestBuilder requestWithCsrf = post("/").param(token.getParameterName(), token.getToken()).session((MockHttpSession) request.getSession());
    this.mockMvc.perform(requestWithCsrf).andExpect(status().isOk());
// @formatter:on
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) HttpSessionCsrfTokenRepository(org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository) CsrfToken(org.springframework.security.web.csrf.CsrfToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 40 with CsrfToken

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

the class CsrfInputTagTests method handleTokenReturnsHiddenInputDifferentTokenValue.

@Test
public void handleTokenReturnsHiddenInputDifferentTokenValue() {
    CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "csrfParameter", "fooBarBazQux");
    String value = this.tag.handleToken(token);
    assertThat(value).as("The returned value should not be null.").isNotNull();
    assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />");
}
Also used : DefaultCsrfToken(org.springframework.security.web.csrf.DefaultCsrfToken) CsrfToken(org.springframework.security.web.csrf.CsrfToken) DefaultCsrfToken(org.springframework.security.web.csrf.DefaultCsrfToken) 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