Search in sources :

Example 91 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project CzechIdMng by bcvsolutions.

the class OAuthAuthenticationManagerTest method testIdentityNotExists.

/**
 * Non-existent identities cannot possess auth. tokens.
 */
@Test
public void testIdentityNotExists() {
    IdmJwtAuthentication authentication = getAuthentication(USER_NAME, DateTime.now().plusHours(1), DateTime.now());
    when(identityService.getByUsername(USER_NAME)).thenReturn(null);
    try {
        authManager.authenticate(authentication);
        Assert.fail("Cannot authenticate unknown identity.");
    } catch (AuthenticationException e) {
        verify(identityService).getByUsername(USER_NAME);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) Test(org.junit.Test) AbstractUnitTest(eu.bcvsolutions.idm.test.api.AbstractUnitTest)

Example 92 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.

the class ShibbolethController method signinHandler.

@RequestMapping(value = { "/signin" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers, ModelAndView mav) {
    LOGGER.info("Headers for shibboleth sign in: {}", headers);
    checkEnabled();
    mav.setViewName("social_link_signin");
    String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
    mav.addObject("providerId", shibIdentityProvider);
    String displayName = institutionalSignInManager.retrieveDisplayName(headers);
    mav.addObject("accountId", displayName);
    RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
    if (remoteUser == null) {
        LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
        identityProviderManager.incrementFailedCount(shibIdentityProvider);
        mav.addObject("unsupportedInstitution", true);
        mav.addObject("institutionContactEmail", identityProviderManager.retrieveContactEmailByProviderid(shibIdentityProvider));
        return mav;
    }
    // Check if the Shibboleth user is already linked to an ORCID account.
    // If so sign them in automatically.
    UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
    if (userConnectionEntity != null) {
        LOGGER.info("Found existing user connection: {}", userConnectionEntity);
        HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
        if (!checkHeadersResult.isSuccess()) {
            mav.addObject("headerCheckFailed", true);
            return mav;
        }
        ProfileEntity profile = profileEntityCacheManager.retrieve(userConnectionEntity.getOrcid());
        if (profile.getUsing2FA()) {
            return new ModelAndView("institutional_2FA");
        }
        try {
            notifyUser(shibIdentityProvider, userConnectionEntity);
            processAuthentication(remoteUser, userConnectionEntity);
        } catch (AuthenticationException e) {
            // this should never happen
            SecurityContextHolder.getContext().setAuthentication(null);
            LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
        }
        return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
    } else {
        // To avoid confusion, force the user to login to ORCID again
        mav.addObject("linkType", "shibboleth");
        mav.addObject("firstName", (headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER));
        mav.addObject("lastName", (headers.get(InstitutionalSignInManager.SN_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.SN_HEADER));
    }
    return mav;
}
Also used : HeaderCheckResult(org.orcid.pojo.HeaderCheckResult) RemoteUser(org.orcid.pojo.RemoteUser) AuthenticationException(org.springframework.security.core.AuthenticationException) ModelAndView(org.springframework.web.servlet.ModelAndView) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 93 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project webanno by webanno.

the class SpringAuthenticatedWebSession method authenticate.

@Override
public boolean authenticate(String username, String password) {
    try {
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        MDC.put(Logging.KEY_USERNAME, username);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.debug("Stored authentication for user [{}] in security context", authentication.getName());
        HttpSession session = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest().getSession();
        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        log.debug("Stored security context in session");
        return true;
    } catch (AuthenticationException e) {
        log.warn("User [{}] failed to login. Reason: {}", username, e.getMessage());
        return false;
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpSession(javax.servlet.http.HttpSession) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 94 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project molgenis by molgenis.

the class AjaxAwareLoginUrlAuthenticationEntryPointTest method testCommenceOther.

@Test
public void testCommenceOther() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getScheme()).thenReturn("http");
    when(request.getServerName()).thenReturn("molgenis.org");
    when(request.getServerPort()).thenReturn(80);
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.encodeRedirectURL("http://molgenis.org/login")).thenReturn("http://molgenis.org/login");
    AuthenticationException authException = mock(AuthenticationException.class);
    ajaxAwareLoginUrlAuthenticationEntryPoint.commence(request, response, authException);
    verify(response).sendRedirect("http://molgenis.org/login");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.testng.annotations.Test)

Example 95 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project molgenis by molgenis.

the class AjaxAwareLoginUrlAuthenticationEntryPointTest method testCommenceRest.

@Test
public void testCommenceRest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    Enumeration<String> headerValueEnumeration = enumeration(singleton("XMLHttpRequest"));
    when(request.getHeader("X-Requested-With")).thenReturn("XMLHttpRequest");
    when(request.getHeaders("X-Requested-With")).thenReturn(headerValueEnumeration);
    HttpServletResponse response = mock(HttpServletResponse.class);
    AuthenticationException authException = mock(AuthenticationException.class);
    ajaxAwareLoginUrlAuthenticationEntryPoint.commence(request, response, authException);
    verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.testng.annotations.Test)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)156 Authentication (org.springframework.security.core.Authentication)78 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)25 Test (org.junit.Test)24 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)15 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 Map (java.util.Map)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6 InternalAuthenticationServiceException (org.springframework.security.authentication.InternalAuthenticationServiceException)6