Search in sources :

Example 1 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project opennms by OpenNMS.

the class SpringSecurityContextServiceTest method setUp.

@Before
public void setUp() throws Exception {
    SecurityContext context = new SecurityContextImpl();
    User principal = new User(USERNAME, PASS, true, true, true, true, Arrays.asList(new GrantedAuthority[] { ROLE_ADMIN, ROLE_PROVISION }));
    org.springframework.security.core.Authentication auth = new PreAuthenticatedAuthenticationToken(principal, new Object());
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);
    this.m_securityContextService = new SpringSecurityContextService();
}
Also used : SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) User(org.springframework.security.core.userdetails.User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Before(org.junit.Before)

Example 2 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project midpoint by Evolveum.

the class InitialDataImport method init.

public void init() throws SchemaException {
    LOGGER.info("Starting initial object import (if necessary).");
    OperationResult mainResult = new OperationResult(OPERATION_INITIAL_OBJECTS_IMPORT);
    Task task = taskManager.createTaskInstance(OPERATION_INITIAL_OBJECTS_IMPORT);
    task.setChannel(SchemaConstants.CHANNEL_GUI_INIT_URI);
    int count = 0;
    int errors = 0;
    File[] files = getInitialImportObjects();
    LOGGER.debug("Files to be imported: {}.", Arrays.toString(files));
    // We need to provide a fake Spring security context here.
    // We have to fake it because we do not have anything in the repository yet. And to get
    // something to the repository we need a context. Chicken and egg. So we fake the egg.
    SecurityContext securityContext = SecurityContextHolder.getContext();
    UserType userAdministrator = new UserType();
    prismContext.adopt(userAdministrator);
    userAdministrator.setName(new PolyStringType(new PolyString("initAdmin", "initAdmin")));
    MidPointPrincipal principal = new MidPointPrincipal(userAdministrator);
    AuthorizationType superAutzType = new AuthorizationType();
    prismContext.adopt(superAutzType, RoleType.class, new ItemPath(RoleType.F_AUTHORIZATION));
    superAutzType.getAction().add(AuthorizationConstants.AUTZ_ALL_URL);
    Authorization superAutz = new Authorization(superAutzType);
    Collection<Authorization> authorities = principal.getAuthorities();
    authorities.add(superAutz);
    Authentication authentication = new PreAuthenticatedAuthenticationToken(principal, null);
    securityContext.setAuthentication(authentication);
    for (File file : files) {
        try {
            LOGGER.debug("Considering initial import of file {}.", file.getName());
            PrismObject object = prismContext.parseObject(file);
            if (ReportType.class.equals(object.getCompileTimeClass())) {
                ReportTypeUtil.applyDefinition(object, prismContext);
            }
            Boolean importObject = importObject(object, file, task, mainResult);
            if (importObject == null) {
                continue;
            }
            if (importObject) {
                count++;
            } else {
                errors++;
            }
        } catch (Exception ex) {
            LoggingUtils.logUnexpectedException(LOGGER, "Couldn't import file {}", ex, file.getName());
            mainResult.recordFatalError("Couldn't import file '" + file.getName() + "'", ex);
        }
    }
    securityContext.setAuthentication(null);
    mainResult.recomputeStatus("Couldn't import objects.");
    LOGGER.info("Initial object import finished ({} objects imported, {} errors)", count, errors);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Initialization status:\n" + mainResult.debugDump());
    }
}
Also used : PolyStringType(com.evolveum.prism.xml.ns._public.types_3.PolyStringType) Task(com.evolveum.midpoint.task.api.Task) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) URISyntaxException(java.net.URISyntaxException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) IOException(java.io.IOException) Authorization(com.evolveum.midpoint.security.api.Authorization) PrismObject(com.evolveum.midpoint.prism.PrismObject) Authentication(org.springframework.security.core.Authentication) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) SecurityContext(org.springframework.security.core.context.SecurityContext) AuthorizationType(com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationType) File(java.io.File) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 3 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project midpoint by Evolveum.

the class MidPointAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String enteredUsername = (String) authentication.getPrincipal();
    LOGGER.trace("Authenticating username '{}'", enteredUsername);
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI);
    Authentication token;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        String enteredPassword = (String) authentication.getCredentials();
        token = passwordAuthenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(enteredUsername, enteredPassword));
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        token = passwordAuthenticationEvaluator.authenticateUserPreAuthenticated(connEnv, enteredUsername);
    } else {
        LOGGER.error("Unsupported authentication {}", authentication);
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }
    MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
    return token;
}
Also used : PasswordAuthenticationContext(com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 4 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project spring-security by spring-projects.

the class GaeAuthenticationFilter method doFilter.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    User googleUser = UserServiceFactory.getUserService().getCurrentUser();
    if (authentication != null && !loggedInUserMatchesGaeUser(authentication, googleUser)) {
        SecurityContextHolder.clearContext();
        authentication = null;
        ((HttpServletRequest) request).getSession().invalidate();
    }
    if (authentication == null) {
        if (googleUser != null) {
            logger.debug("Currently logged on to GAE as user " + googleUser);
            logger.debug("Authenticating to Spring Security");
            // User has returned after authenticating via GAE. Need to authenticate
            // through Spring Security.
            PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(googleUser, null);
            token.setDetails(ads.buildDetails((HttpServletRequest) request));
            try {
                authentication = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                if (authentication.getAuthorities().contains(AppRole.NEW_USER)) {
                    logger.debug("New user authenticated. Redirecting to registration page");
                    ((HttpServletResponse) response).sendRedirect(REGISTRATION_URL);
                    return;
                }
            } catch (AuthenticationException e) {
                failureHandler.onAuthenticationFailure((HttpServletRequest) request, (HttpServletResponse) response, e);
                return;
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) User(com.google.appengine.api.users.User) GaeUser(samples.gae.users.GaeUser) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 5 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationManagerTests method testDetailsEnhancedOnce.

@Test
public void testDetailsEnhancedOnce() throws Exception {
    authentication.setDetails("DETAILS");
    Mockito.when(tokenServices.loadAuthentication("FOO")).thenReturn(authentication);
    PreAuthenticatedAuthenticationToken request = new PreAuthenticatedAuthenticationToken("FOO", "");
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, "BAR");
    OAuth2AuthenticationDetails details = new OAuth2AuthenticationDetails(servletRequest);
    request.setDetails(details);
    Authentication result = manager.authenticate(request);
    // Authenticate the same request again to simulate what happens if the app is caching the result from
    // tokenServices.loadAuthentication():
    result = manager.authenticate(request);
    assertEquals(authentication, result);
    assertEquals("BAR", ((OAuth2AuthenticationDetails) result.getDetails()).getTokenValue());
    assertEquals("DETAILS", ((OAuth2AuthenticationDetails) result.getDetails()).getDecodedDetails());
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.Test)

Aggregations

PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)59 Authentication (org.springframework.security.core.Authentication)34 Test (org.junit.Test)11 SecurityContext (org.springframework.security.core.context.SecurityContext)10 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 User (ca.corefacility.bioinformatics.irida.model.user.User)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)5 AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)4 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)3 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)3 X509Certificate (java.security.cert.X509Certificate)3 ArrayList (java.util.ArrayList)3 OrcidProfileUserDetails (org.orcid.core.oauth.OrcidProfileUserDetails)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)3 PasswordAuthenticationContext (com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext)2 PrismObject (com.evolveum.midpoint.prism.PrismObject)2