Search in sources :

Example 6 with UsernamePassword

use of com.thoughtworks.go.server.newsecurity.models.UsernamePassword in project gocd by gocd.

the class InvalidateAuthenticationOnSecurityConfigChangeFilterTest method shouldInvalidateAuthenticationTokenIfRoleConfigHasChanged.

@Test
void shouldInvalidateAuthenticationTokenIfRoleConfigHasChanged() throws IOException, ServletException {
    request = HttpRequestBuilder.GET("/").withRequestedSessionIdFromSession().build();
    final AuthenticationToken<UsernamePassword> authenticationToken = setupAuthentication();
    SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
    final HttpSession originalSession = request.getSession(false);
    assertThat(SessionUtils.getAuthenticationToken(request).isAuthenticated(clock, systemEnvironment)).isTrue();
    filter.doFilter(request, response, filterChain);
    clock.addSeconds(1);
    filter.onPluginRoleChange();
    response.reset();
    filter.doFilter(request, response, filterChain);
    assertThat(SessionUtils.getAuthenticationToken(request).isAuthenticated(clock, systemEnvironment)).isFalse();
    assertThat(request.getSession(false)).isSameAs(originalSession);
    assertThat(request.getSession(false).getAttribute(SECURITY_CONFIG_LAST_CHANGE)).isEqualTo(clock.currentTimeMillis());
    verify(cacheService, times(1)).invalidateCache();
}
Also used : HttpSession(javax.servlet.http.HttpSession) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword) Test(org.junit.jupiter.api.Test)

Example 7 with UsernamePassword

use of com.thoughtworks.go.server.newsecurity.models.UsernamePassword in project gocd by gocd.

the class ThreadLocalUserFilterTest method shouldSetUserToThreadLocalWhenFilterIsCalledAndRemoveUserFromThreadLocalOnceRequestIsCompleted.

@Test
void shouldSetUserToThreadLocalWhenFilterIsCalledAndRemoveUserFromThreadLocalOnceRequestIsCompleted() throws ServletException, IOException {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final AuthenticationToken<UsernamePassword> authenticationToken = SessionUtilsHelper.createUsernamePasswordAuthentication("bob", "p@ssw0rd", 0L);
    SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
    final GoUserPrinciple[] currentUserInFilter = { null };
    final FilterChain filterChain = new MockFilterChain(mock(Servlet.class), spy(new OncePerRequestFilter() {

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            currentUserInFilter[0] = SessionUtils.getCurrentUser();
        }
    }));
    new ThreadLocalUserFilter().doFilter(request, response, filterChain);
    assertThat(currentUserInFilter[0]).isNotNull();
    assertThat(SessionUtils.getCurrentUser().getUsername()).isEqualTo("anonymous");
    assertThat(SessionUtils.getCurrentUser().getAuthorities()).containsExactly(GoAuthority.ROLE_ANONYMOUS.asAuthority());
}
Also used : MockHttpServletRequest(com.thoughtworks.go.http.mocks.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) MockFilterChain(com.thoughtworks.go.http.mocks.MockFilterChain) MockHttpServletResponse(com.thoughtworks.go.http.mocks.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword) MockHttpServletRequest(com.thoughtworks.go.http.mocks.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) OncePerRequestFilter(org.springframework.web.filter.OncePerRequestFilter) Servlet(javax.servlet.Servlet) GoUserPrinciple(com.thoughtworks.go.server.security.userdetail.GoUserPrinciple) MockFilterChain(com.thoughtworks.go.http.mocks.MockFilterChain) MockHttpServletResponse(com.thoughtworks.go.http.mocks.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 8 with UsernamePassword

use of com.thoughtworks.go.server.newsecurity.models.UsernamePassword in project gocd by gocd.

the class AuthenticationController method performLogin.

@RequestMapping(value = "/auth/security_check", method = RequestMethod.POST)
public RedirectView performLogin(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request) {
    if (securityIsDisabledOrAlreadyLoggedIn(request)) {
        return new RedirectView("/pipelines", true);
    }
    LOGGER.debug("Requesting authentication for form auth.");
    try {
        SavedRequest savedRequest = SessionUtils.savedRequest(request);
        final AuthenticationToken<UsernamePassword> authenticationToken = passwordBasedPluginAuthenticationProvider.authenticate(new UsernamePassword(username, password), null);
        if (authenticationToken == null) {
            return badAuthentication(request, BAD_CREDENTIALS_MSG);
        } else {
            SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
        }
        String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl();
        return new RedirectView(redirectUrl, false);
    } catch (AuthenticationException e) {
        LOGGER.error("Failed to authenticate user: {} ", username, e);
        return badAuthentication(request, e.getMessage());
    } catch (Exception e) {
        return unknownAuthenticationError(request);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) RedirectView(org.springframework.web.servlet.view.RedirectView) AuthenticationException(org.springframework.security.core.AuthenticationException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with UsernamePassword

use of com.thoughtworks.go.server.newsecurity.models.UsernamePassword in project gocd by gocd.

the class AbstractBasicAuthenticationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    try {
        if (isPreviouslyAuthenticated(request)) {
            LOGGER.debug("Request is already authenticated.");
            filterChain.doFilter(request, response);
            return;
        }
        final UsernamePassword credential = BasicAuthHeaderExtractor.extractBasicAuthenticationCredentials(request.getHeader("Authorization"));
        if (credential != null) {
            LOGGER.debug("[Basic Authentication] Authorization header found for user '{}'", credential.getUsername());
        }
        if (securityService.isSecurityEnabled()) {
            LOGGER.debug("Security is enabled.");
            filterWhenSecurityEnabled(request, response, filterChain, credential);
        } else {
            LOGGER.debug("Security is disabled.");
            filterWhenSecurityDisabled(request, response, filterChain, credential);
        }
    } catch (AuthenticationException e) {
        onAuthenticationFailure(request, response, e.getMessage());
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword)

Example 10 with UsernamePassword

use of com.thoughtworks.go.server.newsecurity.models.UsernamePassword in project gocd by gocd.

the class BasicAuthHeaderExtractor method extractBasicAuthenticationCredentials.

public static UsernamePassword extractBasicAuthenticationCredentials(String authorizationHeader) {
    if (isBlank(authorizationHeader)) {
        return null;
    }
    final Matcher matcher = BASIC_AUTH_EXTRACTOR_PATTERN.matcher(authorizationHeader);
    if (matcher.matches()) {
        final String encodedCredentials = matcher.group(1);
        final byte[] decode = Base64.getDecoder().decode(encodedCredentials);
        String decodedCredentials = new String(decode, StandardCharsets.UTF_8);
        final int indexOfSeparator = decodedCredentials.indexOf(':');
        if (indexOfSeparator == -1) {
            throw new BadCredentialsException("Invalid basic authentication credentials specified in request.");
        }
        final String username = decodedCredentials.substring(0, indexOfSeparator);
        final String password = decodedCredentials.substring(indexOfSeparator + 1);
        return new UsernamePassword(username, password);
    }
    return null;
}
Also used : Matcher(java.util.regex.Matcher) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword)

Aggregations

UsernamePassword (com.thoughtworks.go.server.newsecurity.models.UsernamePassword)14 Test (org.junit.jupiter.api.Test)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 HttpSession (javax.servlet.http.HttpSession)4 MockHttpServletResponse (com.thoughtworks.go.http.mocks.MockHttpServletResponse)3 HashMap (java.util.HashMap)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 GsonBuilder (com.google.gson.GsonBuilder)1 MockFilterChain (com.thoughtworks.go.http.mocks.MockFilterChain)1 MockHttpServletRequest (com.thoughtworks.go.http.mocks.MockHttpServletRequest)1 GoUserPrinciple (com.thoughtworks.go.server.security.userdetail.GoUserPrinciple)1 Date (java.util.Date)1 Matcher (java.util.regex.Matcher)1 FilterChain (javax.servlet.FilterChain)1 Servlet (javax.servlet.Servlet)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 SavedRequest (org.springframework.security.web.savedrequest.SavedRequest)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 OncePerRequestFilter (org.springframework.web.filter.OncePerRequestFilter)1