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

The following examples show how to use org.springframework.security.web.csrf.CsrfToken. These examples are extracted from open source projects. 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 Project: blackduck-alert   Source File: HomeController.java    License: 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
@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 3
Source Project: ServiceCutter   Source File: CsrfCookieGeneratorFilter.java    License: 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 4
@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 5
@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 Project: para   Source File: CachedCsrfTokenRepository.java    License: 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 Project: portals-pluto   Source File: RelativePortalURLImpl.java    License: 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 8
Source Project: tutorials   Source File: JWTCsrfTokenRepository.java    License: 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 9
Source Project: openvsx   Source File: UserAPI.java    License: 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 10
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 Project: syndesis   Source File: SyndesisCsrfRepository.java    License: 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 12
Source Project: blackduck-alert   Source File: HomeControllerTestIT.java    License: 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 13
Source Project: multiapps-controller   Source File: CsrfHeadersFilter.java    License: 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 14
Source Project: springsecuritystudy   Source File: AuthApi.java    License: 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;
}
 
Example 15
Source Project: jump-the-queue   Source File: SecurityRestServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@PermitAll
public CsrfToken getCsrfToken(HttpServletRequest request, HttpServletResponse response) {

  CsrfToken token = this.csrfTokenRepository.loadToken(request);
  if (token == null) {
    LOG.error("No CsrfToken could be found - instantiating a new Token");
    token = this.csrfTokenRepository.generateToken(request);
    this.csrfTokenRepository.saveToken(token, request, response);
  }
  return token;
}
 
Example 16
/**
  * The constructor.
  */
 public ApplicationObjectMapperFactory() {

   super();
   // see https://github.com/devonfw-wiki/devon4j/wiki/guide-json#json-and-inheritance
   SimpleModule module = getExtensionModule();
   module.addAbstractTypeMapping(CsrfToken.class, CsrfTokenImpl.class);
// register spring-data Pageable
   module.addSerializer(Pageable.class, new PageableJsonSerializer());
   module.addDeserializer(Pageable.class, new PageableJsonDeserializer());
 }
 
Example 17
/**
 * Test of {@code SecurityRestService.getCsrfToken()}.
 */
@Test
public void testGetCsrfToken() {

  String login = "waiter";
  String password = "waiter";
  SecurityRestService securityService = getServiceClientFactory().create(SecurityRestService.class,
      new ServiceClientConfigBuilder().host("localhost").authBasic().userLogin(login).userPassword(password)
          .buildMap());
  CsrfToken csrfToken = securityService.getCsrfToken(null, null);
  assertThat(csrfToken.getHeaderName()).isEqualTo("X-CSRF-TOKEN");
  assertThat(csrfToken.getParameterName()).isEqualTo("_csrf");
  assertThat(csrfToken.getToken()).isNotNull();
  LOG.debug("Csrf Token: {}", csrfToken.getToken());
}
 
Example 18
@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 19
@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(jwtGenerator.generateCookie(DEFAULT_CSRF_COOKIE_NAME, null, true));
        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 = jwtGenerator.generateCookie(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 20
@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 21
@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 22
Source Project: mojito   Source File: CsrfTokenController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = CSRF_TOKEN_PATH)
@ResponseStatus(HttpStatus.OK)
public String getCsrfToken(HttpServletRequest httpServletRequest) {

    CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CsrfToken.class.getName());

    return csrfToken != null ? csrfToken.getToken() : null;
}
 
Example 23
/**
 * @param request the request, containing method, URI, and headers
 * @param csrfToken the CSRF token to be injected into the request header
 */
protected void injectCsrfTokenIntoHeader(HttpRequest request, CsrfToken csrfToken) {
    if (csrfToken == null) {
        throw new SessionAuthenticationException("There is no CSRF token to inject");
    }

    logger.debug("Injecting CSRF token into request {} header: {}", request.getURI(), csrfToken.getToken());
    request.getHeaders().add(csrfToken.getHeaderName(), csrfToken.getToken());
}
 
Example 24
/**
 * 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 25
Source Project: spring-boot-cookbook   Source File: CsrfController.java    License: 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 26
@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 27
@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 28
@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 29
@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 30
Source Project: eds-starter6-jpa   Source File: CsrfController.java    License: 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;
}