Search in sources :

Example 46 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class ResourceOwnerPasswordTokenGranterTests method testAccountLocked.

@Test(expected = InvalidGrantException.class)
public void testAccountLocked() {
    ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(new AuthenticationManager() {

        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            throw new LockedException("test");
        }
    }, providerTokenServices, clientDetailsService, requestFactory);
    granter.grant("password", tokenRequest);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) LockedException(org.springframework.security.authentication.LockedException) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) Test(org.junit.Test)

Example 47 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class ResourceOwnerPasswordTokenGranterTests method testExtraParameters.

@Test
public void testExtraParameters() {
    authenticationManager = new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) authentication;
                user = new UsernamePasswordAuthenticationToken(user.getPrincipal(), "N/A", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
                @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails();
                assertNull(details.get("password"));
                return user;
            }
            return authentication;
        }
    };
    ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory);
    OAuth2AccessToken token = granter.grant("password", tokenRequest);
    OAuth2Authentication authentication = providerTokenServices.loadAuthentication(token.getValue());
    assertTrue(authentication.isAuthenticated());
    assertNull(authentication.getUserAuthentication().getDetails());
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 48 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project libresonic by Libresonic.

the class RESTRequestParameterProcessingFilter method authenticate.

private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {
    // Previously authenticated and username not overridden?
    if (username == null && previousAuth != null) {
        return null;
    }
    if (salt != null && token != null) {
        User user = securityService.getUserByName(username);
        if (user == null) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
        if (!expectedToken.equals(token)) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        password = user.getPassword();
    }
    if (password != null) {
        try {
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authResult = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(authResult);
            return null;
        } catch (AuthenticationException x) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
    }
    return RESTController.ErrorCode.MISSING_PARAMETER;
}
Also used : User(org.libresonic.player.domain.User) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 49 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;
        }
        try {
            // Check if the user has been notified
            if (!UserConnectionStatus.NOTIFIED.equals(userConnectionEntity.getConnectionSatus())) {
                try {
                    institutionalSignInManager.sendNotification(userConnectionEntity.getOrcid(), shibIdentityProvider);
                    userConnectionEntity.setConnectionSatus(UserConnectionStatus.NOTIFIED);
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("Unable to send institutional sign in notification to user " + userConnectionEntity.getOrcid(), e);
                }
            }
            PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), remoteUser.getUserId());
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            userConnectionEntity.setLastLogin(new Date());
            userConnectionManager.update(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) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) Date(java.util.Date) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 50 with AuthenticationException

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

the class OpenClinicaUsernamePasswordAuthenticationFilter method attemptAuthentication.

//~ Methods ========================================================================================================
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    String username = obtainUsername(request);
    String password = obtainPassword(request);
    if (username == null) {
        username = "";
    }
    if (password == null) {
        password = "";
    }
    username = username.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
    // Place the last username attempted into HttpSession for views
    HttpSession session = request.getSession(false);
    if (session != null || getAllowSessionCreation()) {
        request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
    }
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
    Authentication authentication = null;
    UserAccountBean userAccountBean = null;
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    try {
        EntityBean eb = getUserAccountDao().findByUserName(username);
        userAccountBean = eb.getId() != 0 ? (UserAccountBean) eb : null;
        authentication = this.getAuthenticationManager().authenticate(authRequest);
        auditUserLogin(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
        resetLockCounter(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
    } catch (LockedException le) {
        auditUserLogin(username, LoginStatus.FAILED_LOGIN_LOCKED, userAccountBean);
        throw le;
    } catch (BadCredentialsException au) {
        auditUserLogin(username, LoginStatus.FAILED_LOGIN, userAccountBean);
        lockAccount(username, LoginStatus.FAILED_LOGIN, userAccountBean);
        throw au;
    } catch (AuthenticationException ae) {
        throw ae;
    }
    return authentication;
}
Also used : Locale(java.util.Locale) LockedException(org.springframework.security.authentication.LockedException) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) EntityBean(org.akaza.openclinica.bean.core.EntityBean) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)50 Authentication (org.springframework.security.core.Authentication)27 Test (org.junit.Test)22 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 HttpServletResponse (javax.servlet.http.HttpServletResponse)12 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)11 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)7 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)5 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 ServletException (javax.servlet.ServletException)3 HttpSession (javax.servlet.http.HttpSession)3 LockedException (org.springframework.security.authentication.LockedException)3 Map (java.util.Map)2 LoginException (javax.security.auth.login.LoginException)2 FilterChain (javax.servlet.FilterChain)2 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)2