org.springframework.security.web.csrf.CsrfToken Java Examples

The following examples show how to use org.springframework.security.web.csrf.CsrfToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HomeController.java    From blackduck-alert with Apache License 2.0 7 votes vote down vote up
@GetMapping(value = "/api/verify")
public ResponseEntity<String> checkAuthentication(final HttpServletRequest request) {
    final HttpServletRequest httpRequest = request;
    final CsrfToken csrfToken = csrfTokenRespository.loadToken(request);
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final boolean isAnonymous = authentication.getAuthorities().stream()
                                    .map(GrantedAuthority::getAuthority)
                                    .anyMatch(authority -> authority.equals(ROLE_ANONYMOUS));
    final boolean authorized = authentication.isAuthenticated() && !isAnonymous && csrfToken != null;

    if (!authorized) {
        httpRequest.getSession().invalidate();
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    } else {
        final HttpHeaders headers = new HttpHeaders();
        headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
        return responseFactory.createResponse(HttpStatus.NO_CONTENT, headers, null);
    }
}
 
Example #2
Source File: JWTCsrfTokenRepository.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public CsrfToken generateToken(HttpServletRequest request) {
    String id = UUID.randomUUID()
        .toString()
        .replace("-", "");

    Date now = new Date();
    Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds

    String token = Jwts.builder()
        .setId(id)
        .setIssuedAt(now)
        .setNotBefore(now)
        .setExpiration(exp)
        .signWith(SignatureAlgorithm.HS256, secret)
        .compact();

    return new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", token);
}
 
Example #3
Source File: _CsrfCookieGeneratorFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example #4
Source File: RelativePortalURLImpl.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a PortalURLImpl instance using customized port.
 * 
 * @param urlBase
 *           the absolute (protocol://domain:port) request url base
 * @param contextPath
 *           the servlet context path.
 * @param servletName
 *           the servlet name.
 * @param urlParser
 *           the {@link PortalURLParser} used to construct a string
 *           representation of the url.
 */
public RelativePortalURLImpl(String urlBase, String contextPath,
      String servletName, PortalURLParser urlParser, HttpServletRequest req) {
   this.urlBase = urlBase;
   StringBuffer buffer = new StringBuffer();
   buffer.append(contextPath);
   buffer.append(servletName);
   servletPath = buffer.toString();
   this.urlParser = urlParser;
   this.servletRequest = req;
   this.cloneId = (++cloneCtr) + 10000;
   CsrfToken csrfToken = (CsrfToken)req.getAttribute(CsrfToken.class.getName());
   this.csrfParameterName = csrfToken.getParameterName();
   this.csrfParameterValue = csrfToken.getToken();
   if (isDebug) {
      LOG.debug("Constructed URL, clone ID: " + cloneId);
   }
}
 
Example #5
Source File: CsrfCookieGeneratorFilter.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example #6
Source File: CachedCsrfTokenRepository.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a CSRF token from cache.
 * @param request HTTP request
 * @return the token
 */
public CsrfToken loadToken(HttpServletRequest request) {
	CsrfToken token = null;
	String ident = getIdentifierFromCookie(request);
	if (ident != null) {
		String key = ident.concat(parameterName);
		token = loadTokenFromCache(key);
		String anonid = HttpUtils.getStateParam(anonIdentCookieName, request);
		if (anonid != null) {
			CsrfToken anonToken = loadTokenFromCache(anonid);
			if (!ident.equals(anonid) && anonToken != null && token != null) {
				// sync anon and auth csrf tokens
				//storeTokenInCache(anonid, token);
				storeTokenInCache(ident, anonToken);
				token = anonToken;
			}
		}
	}
	if (token != null && !StringUtils.isBlank(token.getToken()) && StringUtils.isBlank(getTokenFromCookie(request))) {
		token = null;
	}
	return token;
}
 
Example #7
Source File: CsrfCookieGeneratorFilter.java    From expper with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example #8
Source File: CsrfCookieGeneratorFilter.java    From demo-spring-security-cas with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example #9
Source File: CsrfController.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
/**
 * http://docs.spring.io/spring-security/site/docs/4.2.x/reference/htmlsingle/#websocket-sameorigin-csrf
 *
 * @param token
 * @return
 */
@RequestMapping("/csrf")
public CsrfToken csrf(CsrfToken token) {
    /**
     * {"headerName":"X-CSRF-TOKEN","parameterName":"_csrf","token":"b7ce0199-206b-449c-b17a-66f665a94a38"}
     */
    return token;
}
 
Example #10
Source File: UnieapSecurityConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
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);
		}
	};
}
 
Example #11
Source File: CookieCsrfSignedTokenRepository.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public CsrfToken generateToken(HttpServletRequest request) {

    CsrfToken csrfToken = loadToken(request);
    if (csrfToken != null) {
        return csrfToken;
    }

    UUID token = UUID.randomUUID();
    return new DefaultCsrfToken(DEFAULT_CSRF_HEADER_NAME, DEFAULT_CSRF_PARAMETER_NAME, token.toString());
}
 
Example #12
Source File: CookieCsrfSignedTokenRepository.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void saveToken(CsrfToken token, HttpServletRequest request,
                      HttpServletResponse response) {

    if(request.getAttribute(DEFAULT_CSRF_COOKIE_NAME) != null) {
        // Token already persisted in cookie.
        return;
    }

    if(token == null) {
        // Null token means delete it.
        response.addCookie(cookieGenerator.generate(DEFAULT_CSRF_COOKIE_NAME, null));
        return;
    }

    String tokenValue = token.getToken();

    try {
        JWTClaimsSet claims = new JWTClaimsSet.Builder()
                .issuer(issuer)
                .issueTime(new Date())
                .claim(TOKEN_CLAIM, tokenValue)
                .build();

        JWSObject jwsObject = new JWSObject(new JWSHeader((JWSAlgorithm.HS256)), new Payload(claims.toJSONObject()));
        jwsObject.sign(signer);

        Cookie cookie = cookieGenerator.generate(DEFAULT_CSRF_COOKIE_NAME, jwsObject.serialize(), true);
        response.addCookie(cookie);
        request.setAttribute(DEFAULT_CSRF_COOKIE_NAME, true);
    } catch (JOSEException ex) {
        LOGGER.error("Unable to generate CSRF token", ex);
    }
}
 
Example #13
Source File: CookieCsrfSignedTokenRepository.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public CsrfToken loadToken(HttpServletRequest request) {

    Cookie cookie = WebUtils.getCookie(request, DEFAULT_CSRF_COOKIE_NAME);
    if (cookie == null) {
        return null;
    }
    String cookieValue = cookie.getValue();
    if (!StringUtils.hasLength(cookieValue)) {
        return null;
    }

    try {
        JWSObject jws = JWSObject.parse(cookieValue);

        if (jws.verify(verifier)) {
            String token = jws.getPayload().toJSONObject().getAsString(TOKEN_CLAIM);

            if (!StringUtils.hasLength(token)) {
                return null;
            }

            return new DefaultCsrfToken(DEFAULT_CSRF_HEADER_NAME, DEFAULT_CSRF_PARAMETER_NAME, token);
        }
    } catch (ParseException | JOSEException ex) {
        LOGGER.error("Unable to verify CSRF token", ex);
    }

    return null;
}
 
Example #14
Source File: CsrfIncludeFilter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    httpResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken());

    chain.doFilter(request, response);
}
 
Example #15
Source File: CsrfController.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
public static String getCsrfToken(HttpServletRequest request) {
	CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
	if (token != null) {
		return token.getToken();
	}
	return null;
}
 
Example #16
Source File: CachedCsrfTokenRepository.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Saves a CSRF token in cache.
 * @param t (ignored)
 * @param request HTTP request
 * @param response HTTP response
 */
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) {
	String ident = getIdentifierFromCookie(request);
	if (StringUtils.isBlank(ident) && StringUtils.isBlank(HttpUtils.getStateParam(authCookie, request))) {
		ident = Utils.generateSecurityToken(16);
		storeAnonIdentCookie(ident, request, response);
	}
	if (ident != null) {
		CsrfToken token = loadToken(request);
		if (token == null) {
			String anonid = HttpUtils.getStateParam(anonIdentCookieName, request);
			if (anonid != null) {
				token = loadTokenFromCache(ident);
				if (token == null) {
					HttpUtils.removeStateParam(cookieName, request, response);
					HttpUtils.removeStateParam(anonIdentCookieName, request, response);
					removeTokenFromCache(ident);
					return;
				}
			} else {
				token = generateToken(null);
			}
			storeTokenInCache(ident, token);
		}
		storeTokenAsCookie(token, request, response);
	}
}
 
Example #17
Source File: CachedCsrfTokenRepository.java    From para with Apache License 2.0 5 votes vote down vote up
private void storeTokenInCache(String key, CsrfToken token) {
	if (!key.endsWith(parameterName)) {
		key = key.concat(parameterName);
	}
	if (Config.isCacheEnabled()) {
		cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC);
	} else {
		localCache.put(key, new Object[]{token, System.currentTimeMillis()});
	}
}
 
Example #18
Source File: CachedCsrfTokenRepository.java    From para with Apache License 2.0 5 votes vote down vote up
private void storeTokenAsCookie(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
	if (isValidButNotInCookie(token, request)) {
		Cookie c = new Cookie(cookieName, token.getToken());
		c.setMaxAge(Config.SESSION_TIMEOUT_SEC);
		// don't enable HttpOnly - javascript can't access the cookie if enabled
		c.setHttpOnly(false);
		c.setSecure("https".equalsIgnoreCase(request.getScheme()));
		c.setPath("/");
		response.addCookie(c);
	}
}
 
Example #19
Source File: PageState.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor. Access the classes containing the necessary data.
 * 
 * @param request
 */
public PageState(HttpServletRequest request) {
   portalRC = PortalRequestContext.getContext(request);
   portalUrl = portalRC.getRequestedPortalURL();
   drvrConfig = (DriverConfiguration) portalRC.getServletContext().getAttribute(AttributeKeys.DRIVER_CONFIG);
   servletContext = portalRC.getServletContext();
   pageConfig = portalUrl.getPageConfig(servletContext);
   csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
}
 
Example #20
Source File: CsrfController.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/api/csrf", method = RequestMethod.GET)
public CsrfToken csrf(CsrfToken token) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("CSRF Token - Name: %s, Token: %s", token.getHeaderName(), token.getToken()));
    }
    return token;
}
 
Example #21
Source File: IndexController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/authentication")
public void getLoginPage(@RequestParam(value="failed", required = false) String failed, @RequestParam(value = "recaptchaFailed", required = false) String recaptchaFailed,
                         Model model,
                         Principal principal,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
    if(principal != null) {
        response.sendRedirect("/admin/");
        return;
    }
    model.addAttribute("failed", failed != null);
    model.addAttribute("recaptchaFailed", recaptchaFailed != null);
    model.addAttribute("hasRecaptchaApiKey", false);

    //
    model.addAttribute("request", request);
    model.addAttribute("demoModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO)));
    model.addAttribute("devModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEV)));
    model.addAttribute("prodModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
    model.addAttribute(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
    //

    var configuration = configurationManager.getFor(EnumSet.of(RECAPTCHA_API_KEY, ENABLE_CAPTCHA_FOR_LOGIN), ConfigurationLevel.system());

    configuration.get(RECAPTCHA_API_KEY).getValue()
        .filter(key -> configuration.get(ENABLE_CAPTCHA_FOR_LOGIN).getValueAsBooleanOrDefault(true))
        .ifPresent(key -> {
            model.addAttribute("hasRecaptchaApiKey", true);
            model.addAttribute("recaptchaApiKey", key);
        });
    try (var os = response.getOutputStream()) {
        response.setContentType(TEXT_HTML_CHARSET_UTF_8);
        response.setCharacterEncoding(UTF_8);
        var nonce = addCspHeader(response);
        model.addAttribute("nonce", nonce);
        templateManager.renderHtml(new ClassPathResource("alfio/web-templates/login.ms"), model.asMap(), os);
    }
}
 
Example #22
Source File: IndexController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/admin")
public void adminHome(Model model, @Value("${alfio.version}") String version, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException {
    model.addAttribute("alfioVersion", version);
    model.addAttribute("username", principal.getName());
    model.addAttribute("basicConfigurationNeeded", configurationManager.isBasicConfigurationNeeded());

    boolean isDBAuthentication = !(principal instanceof WebSecurityConfig.OpenIdAlfioAuthentication);
    model.addAttribute("isDBAuthentication", isDBAuthentication);
    if (!isDBAuthentication) {
        String idpLogoutRedirectionUrl = ((WebSecurityConfig.OpenIdAlfioAuthentication) SecurityContextHolder.getContext().getAuthentication()).getIdpLogoutRedirectionUrl();
        model.addAttribute("idpLogoutRedirectionUrl", idpLogoutRedirectionUrl);
    } else {
        model.addAttribute("idpLogoutRedirectionUrl", null);
    }

    Collection<String> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities()
        .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

    boolean isAdmin = authorities.contains(Role.ADMIN.getRoleName());
    model.addAttribute("isOwner", isAdmin || authorities.contains(Role.OWNER.getRoleName()));
    model.addAttribute("isAdmin", isAdmin);
    //
    model.addAttribute("request", request);
    model.addAttribute("demoModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO)));
    model.addAttribute("devModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEV)));
    model.addAttribute("prodModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
    model.addAttribute(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
    //

    try (var os = response.getOutputStream()) {
        response.setContentType(TEXT_HTML_CHARSET_UTF_8);
        response.setCharacterEncoding(UTF_8);
        var nonce = addCspHeader(response);
        model.addAttribute("nonce", nonce);
        templateManager.renderHtml(new ClassPathResource("alfio/web-templates/admin-index.ms"), model.asMap(), os);
    }
}
 
Example #23
Source File: WebSecurityConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // NOTE: A real implementation should have a nonce cache so the token cannot be reused

    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");

    if (
    // only care if it's a POST
    "POST".equals(request.getMethod()) &&
    // ignore if the request path is in our list
        Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
        // make sure we have a token
        token != null) {
        // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
        try {
            Jwts.parser()
                .setSigningKeyResolver(secretService.getSigningKeyResolver())
                .parseClaimsJws(token.getToken());
        } catch (JwtException e) {
            // most likely an ExpiredJwtException, but this will handle any
            request.setAttribute("exception", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt");
            dispatcher.forward(request, response);
        }
    }

    filterChain.doFilter(request, response);
}
 
Example #24
Source File: JWTCsrfTokenRepository.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public CsrfToken loadToken(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session == null || "GET".equals(request.getMethod())) {
        return null;
    }
    return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
}
 
Example #25
Source File: FormLoginAuthenticationCsrfTokenInterceptor.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the CSRF token from login html because the CSRF token endpoint needs
 * to be authenticated first.
 *
 * @param loginHtml The login page HTML which contains the csrf token. It is
 * assumed that the CSRF token is embedded on the page inside an input field
 * with name matching
 * {@link com.box.l10n.mojito.rest.resttemplate.FormLoginAuthenticationCsrfTokenInterceptor#CSRF_PARAM_NAME}
 * @return
 * @throws AuthenticationException
 */
protected CsrfToken getCsrfTokenFromLoginHtml(String loginHtml) throws AuthenticationException {
    Pattern pattern = Pattern.compile("CSRF_TOKEN = '(.*?)';");
    Matcher matcher = pattern.matcher(loginHtml);

    if (matcher.find()) {
        String csrfTokenString = matcher.group(1);

        logger.debug("CSRF token from login html: {}", csrfTokenString);
        return new DefaultCsrfToken(CSRF_HEADER_NAME,
                CSRF_PARAM_NAME, csrfTokenString);
    } else {
        throw new SessionAuthenticationException("Could not find CSRF_TOKEN variable on login page");
    }
}
 
Example #26
Source File: UserAPI.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
@GetMapping(
    path = "/user/csrf",
    produces = MediaType.APPLICATION_JSON_VALUE
)
public CsrfTokenJson getCsrfToken(HttpServletRequest request) {
    var csrfToken = (CsrfToken) request.getAttribute("_csrf");
    if (csrfToken == null) {
        return CsrfTokenJson.error("Token is not available.");
    }
    var json = new CsrfTokenJson();
    json.value = csrfToken.getToken();
    json.header = csrfToken.getHeaderName();
    return json;
}
 
Example #27
Source File: SyndesisCsrfRepository.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public CsrfToken loadToken(HttpServletRequest httpServletRequest) {
    Optional<String> token = extractToken(httpServletRequest);
    if (token.isPresent()) {
        LOG.trace("Xsrf token found in request to uri {}. Value is: {}", httpServletRequest.getRequestURI(), token.get());
    } else {
        LOG.trace("Xsrf token not found in request to uri {}", httpServletRequest.getRequestURI());
    }
    return token.map(val -> new DefaultCsrfToken(XSRF_HEADER_NAME, XSRF_HEADER_NAME, val)).orElse(null);
}
 
Example #28
Source File: HomeControllerTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
@WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN)
public void testVerify() throws Exception {
    final HttpHeaders headers = new HttpHeaders();
    final MockHttpSession session = new MockHttpSession();
    final ServletContext servletContext = webApplicationContext.getServletContext();

    final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get(HOME_VERIFY_URL).with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN));
    request.session(session);
    final HttpServletRequest httpServletRequest = request.buildRequest(servletContext);
    final CsrfToken csrfToken = csrfTokenRepository.generateToken(httpServletRequest);
    csrfTokenRepository.saveToken(csrfToken, httpServletRequest, null);
    headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
    mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isNoContent());
}
 
Example #29
Source File: CsrfHeadersFilter.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
    CsrfToken token = (CsrfToken) request.getAttribute(SPRING_SECURITY_CSRF_SESSION_ATTRIBUTE);
    if (token != null) {
        response.setHeader(Constants.CSRF_HEADER_NAME, token.getHeaderName());
        response.setHeader(Constants.CSRF_PARAM_NAME, token.getParameterName());
        response.setHeader(Constants.CSRF_TOKEN, token.getToken());
    }
    filterChain.doFilter(request, response);
}
 
Example #30
Source File: AuthApi.java    From springsecuritystudy with MIT License 5 votes vote down vote up
@RequestMapping(value="csrf-token")
public JSONResponse getCsrfToken(HttpServletRequest request) {
    JSONResponse jsonResponse = new JSONResponse();
    CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    String token = csrfToken.getToken();
    jsonResponse.addMsg("csrfToken", token);
    return jsonResponse;
}