Search in sources :

Example 1 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project ORCID-Source by ORCID.

the class BaseController method logoutCurrentUser.

protected void logoutCurrentUser(HttpServletRequest request, HttpServletResponse response) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (internalSSOManager.enableCookie()) {
        Cookie[] cookies = request.getCookies();
        // Delete cookie and token associated with that cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (InternalSSOManager.COOKIE_NAME.equals(cookie.getName())) {
                    try {
                        // If it is a valid cookie, extract the orcid value
                        // and
                        // remove the token and the cookie
                        @SuppressWarnings("unchecked") HashMap<String, String> cookieValues = JsonUtils.readObjectFromJsonString(cookie.getValue(), HashMap.class);
                        if (cookieValues.containsKey(InternalSSOManager.COOKIE_KEY_ORCID) && !PojoUtil.isEmpty(cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID))) {
                            internalSSOManager.deleteToken(cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID), request, response);
                        } else {
                            // If it is not valid, just remove the cookie
                            cookie.setValue(StringUtils.EMPTY);
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    } catch (RuntimeException re) {
                        // If any exception happens, but, the cookie exists,
                        // remove the cookie
                        cookie.setValue(StringUtils.EMPTY);
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                    break;
                }
            }
        }
        // Delete token if exists
        if (authentication != null && !PojoUtil.isEmpty(authentication.getName())) {
            internalSSOManager.deleteToken(authentication.getName());
        }
    }
    if (authentication != null && authentication.isAuthenticated()) {
        new SecurityContextLogoutHandler().logout(request, response, authentication);
    }
    CsrfToken token = csrfTokenRepository.generateToken(request);
    csrfTokenRepository.saveToken(token, request, response);
    request.setAttribute("_csrf", token);
}
Also used : Cookie(javax.servlet.http.Cookie) SecurityContextLogoutHandler(org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler) Authentication(org.springframework.security.core.Authentication) CsrfToken(org.springframework.security.web.csrf.CsrfToken)

Example 2 with CsrfToken

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

the class LoginHandler method authenticateUser.

public ResponseEntity<String> authenticateUser(final HttpServletRequest request, final HttpServletResponse response, final LoginRestModel loginRestModel) {
    final IntLogger logger = new PrintStreamIntLogger(System.out, LogLevel.INFO);
    try {
        if (loginActions.authenticateUser(loginRestModel, logger)) {
            final CsrfToken token = csrfTokenRepository.generateToken(request);
            csrfTokenRepository.saveToken(token, request, response);
            response.setHeader(token.getHeaderName(), token.getToken());
            return createResponse(HttpStatus.OK, "{\"message\":\"Success\"}");
        }
        return createResponse(HttpStatus.UNAUTHORIZED, "User not administrator");
    } catch (final IntegrationRestException e) {
        logger.error(e.getMessage(), e);
        return createResponse(HttpStatus.valueOf(e.getHttpStatusCode()), e.getHttpStatusMessage() + " : " + e.getMessage());
    } catch (final AlertFieldException e) {
        logger.error(e.getMessage(), e);
        final ResponseBodyBuilder responseBodyBuilder = new ResponseBodyBuilder(0L, e.getMessage());
        responseBodyBuilder.putErrors(e.getFieldErrors());
        final String responseBody = responseBodyBuilder.build();
        return createResponse(HttpStatus.BAD_REQUEST, responseBody);
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
        return createResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : IntegrationRestException(com.blackducksoftware.integration.hub.rest.exception.IntegrationRestException) PrintStreamIntLogger(com.blackducksoftware.integration.log.PrintStreamIntLogger) IntLogger(com.blackducksoftware.integration.log.IntLogger) PrintStreamIntLogger(com.blackducksoftware.integration.log.PrintStreamIntLogger) AlertFieldException(com.blackducksoftware.integration.hub.alert.exception.AlertFieldException) CsrfToken(org.springframework.security.web.csrf.CsrfToken) AlertFieldException(com.blackducksoftware.integration.hub.alert.exception.AlertFieldException) IntegrationRestException(com.blackducksoftware.integration.hub.rest.exception.IntegrationRestException) ResponseBodyBuilder(com.blackducksoftware.integration.hub.alert.web.model.ResponseBodyBuilder)

Example 3 with CsrfToken

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

the class HomeControllerTestIT method testVerify.

@Test
@WithMockUser(roles = "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(homeVerifyUrl).with(SecurityMockMvcRequestPostProcessors.user("admin").roles("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().isOk());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockHttpSession(org.springframework.mock.web.MockHttpSession) ServletContext(javax.servlet.ServletContext) CsrfToken(org.springframework.security.web.csrf.CsrfToken) WithMockUser(org.springframework.security.test.context.support.WithMockUser) ExternalConnectionTest(com.blackducksoftware.integration.test.annotation.ExternalConnectionTest) Test(org.junit.Test)

Example 4 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project vorto by eclipse.

the class AngularCsrfHeaderFilter method doFilterInternal.

@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, "XSRF-TOKEN");
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
    filterChain.doFilter(request, response);
}
Also used : Cookie(javax.servlet.http.Cookie) CsrfToken(org.springframework.security.web.csrf.CsrfToken)

Example 5 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project microservices by pwillhan.

the class SsoUiApplication 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 = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    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)

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