org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken Java Examples

The following examples show how to use org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecuritySessionResource.java    From secure-data-service with Apache License 2.0 7 votes vote down vote up
/**
 * Method processing HTTP GET requests to the logout resource, and producing "application/json"
 * MIME media
 * type.
 *
 * @return HashMap indicating success or failure for logout action (matches type
 *         "application/json" through jersey).
 */
@GET
@Path("logout")
public Map<String, Object> logoutUser(@Context HttpHeaders headers, @Context UriInfo uriInfo) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Authentication oAuth = ((OAuth2Authentication) auth).getUserAuthentication();

    Map<String, Object> logoutMap = new HashMap<String, Object>();
    logoutMap.put("logout", true);
    logoutMap.put("msg", "You are logged out of SLI");
    if (oAuth instanceof PreAuthenticatedAuthenticationToken) {
        PreAuthenticatedAuthenticationToken userAuth = (PreAuthenticatedAuthenticationToken) oAuth;
        logoutMap.put("logout", this.sessionManager.logout((String) userAuth.getCredentials()));
    }

    String status = (Boolean) logoutMap.get("logout") ? "Success" : "Failure";
    auditLogger.audit(securityEventBuilder.createSecurityEvent(SecuritySessionResource.class.getName(),
            uriInfo.getRequestUri(), "Logout: " + status, true));
    return logoutMap;
}
 
Example #2
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void setRealmAdminContext() {
    String user = "realmadmin";
    String fullName = "Realm Administrator";
    List<String> roles = Arrays.asList(RoleInitializer.REALM_ADMINISTRATOR);

    Entity entity = Mockito.mock(Entity.class);
    Mockito.when(entity.getType()).thenReturn("admin-staff");
    Mockito.when(entity.getEntityId()).thenReturn(user);
    SLIPrincipal principal = buildPrincipal(user, fullName, DEFAULT_REALM_ID, roles, entity, "fake-ed-org", new EdOrgContextRightsCache());
    principal.setRoles(roles);
    principal.setTenantId(TENANT_ID);
    principal.setAdminRealmAuthenticated(true);
    setSecurityContext(principal, false);

    Right[] rights = new Right[] {  Right.ADMIN_ACCESS, Right.READ_GENERAL, Right.CRUD_REALM, Right.READ_PUBLIC, Right.CRUD_ROLE };
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(SecurityContextHolder
            .getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext()
            .getAuthentication().getCredentials(), Arrays.asList(rights));
    SecurityContextHolder.getContext().setAuthentication(token);

    SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT);
}
 
Example #3
Source File: JsonWebTokenAuthenticationProvider.java    From trivia-microservices with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	Authentication authenticatedUser = null;
	// Only process the PreAuthenticatedAuthenticationToken
	if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class)
			&& authentication.getPrincipal() != null) {
		String tokenHeader = (String) authentication.getPrincipal();
		UserDetails userDetails = parseToken(tokenHeader);
		if (userDetails != null) {
			authenticatedUser = new JsonWebTokenAuthentication(userDetails, tokenHeader);
		}
	} else {
		// It is already a JsonWebTokenAuthentication
		authenticatedUser = authentication;
	}
	return authenticatedUser;
}
 
Example #4
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void setDeveloperContext() {
    String user = "developer";
    String fullName = "App Developer";
    List<String> roles = Arrays.asList(RoleInitializer.APP_DEVELOPER);

    Entity entity = Mockito.mock(Entity.class);
    Mockito.when(entity.getType()).thenReturn("admin-staff");
    Mockito.when(entity.getEntityId()).thenReturn(user);
    SLIPrincipal principal = buildPrincipal(user, fullName, DEFAULT_REALM_ID, roles, entity, ED_ORG_ID, new EdOrgContextRightsCache());
    principal.setExternalId("developer");
    principal.setRoles(roles);
    principal.setAdminRealmAuthenticated(true);
    setSecurityContext(principal, true);

    Right[] rights = new Right[] { Right.ADMIN_ACCESS, Right.DEV_APP_CRUD, Right.READ_PUBLIC };
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(SecurityContextHolder
            .getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext()
            .getAuthentication().getCredentials(), Arrays.asList(rights));

    LOG.debug("elevating rights to {}", Arrays.toString(rights));
    SecurityContextHolder.getContext().setAuthentication(token);
    SecurityUtil.setUserContext(SecurityUtil.UserContext.NO_CONTEXT);
}
 
Example #5
Source File: SpringAuthenticatedWebSession.java    From webanno with Apache License 2.0 6 votes vote down vote up
public SpringAuthenticatedWebSession(Request request)
{
    super(request);
    injectDependencies();
    ensureDependenciesNotNull();
    
    // If the a proper (non-anonymous) authentication has already been performed (e.g. via
    // external pre-authentication) then also mark the Wicket session as signed-in.
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (
            authentication != null && 
            authentication.isAuthenticated() && 
            authentication instanceof PreAuthenticatedAuthenticationToken
            //!(authentication instanceof AnonymousAuthenticationToken && !isSignedIn())
    ) {
        signIn(true);
    }
}
 
Example #6
Source File: ApiAuthenticationUserDetailsService.java    From todolist with MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
	String principal = (String) token.getPrincipal();

	UserDetails result = null;
	if(!Strings.isNullOrEmpty(principal)) {
		logger.debug(principal);
		String[] slices = principal.split(":");
		String email = slices[0];
		String secret = slices[1];

		try {
			AccessToken p = accessTokenService.valid(email, secret);
			result = userService.findByEmail(p.getEmail());
		} catch(Exception ex) {
			throw new UsernameNotFoundException("");
		}
	}

	return result;
}
 
Example #7
Source File: AmqpControllerAuthentication.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
private static PreAuthenticatedAuthenticationToken createAuthentication(final PreAuthenticationFilter filter,
        final DmfTenantSecurityToken secruityToken) {

    if (!filter.isEnable(secruityToken)) {
        return null;
    }

    final Object principal = filter.getPreAuthenticatedPrincipal(secruityToken);
    final Object credentials = filter.getPreAuthenticatedCredentials(secruityToken);

    if (principal == null) {
        LOGGER.debug("No pre-authenticated principal found in message");
        return null;
    }

    LOGGER.debug("preAuthenticatedPrincipal = {} trying to authenticate", principal);

    return new PreAuthenticatedAuthenticationToken(principal, credentials,
            filter.getSuccessfulAuthenticationAuthorities());
}
 
Example #8
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test(expected = InsufficientAuthenticationException.class)
public void principalAndCredentialsAreTheSameSourceIpListNotMatches() {
    final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" };
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

    final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider(
            trustedIPAddresses);

    // test, should throw authentication exception
    final Authentication authenticate = underTestWithList.authenticate(token);
    try {
        assertThat(authenticate.isAuthenticated()).isTrue();
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
 
Example #9
Source File: SecurityAdviceTestTwo.java    From cosmo with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    this.advice = new SecurityAdvice(securityManager,contentDao,userDao);        
    Authentication authentication = new PreAuthenticatedAuthenticationToken(U_SHAREE, "passwd");
    Set<Ticket> tickets = Collections.emptySet();
    CosmoSecurityContext context = new CosmoSecurityContextImpl(authentication, tickets, sharee);
    when(securityManager.getSecurityContext()).thenReturn(context);

    when(collection.getOwner()).thenReturn(sharer);
    when(collection.getUid()).thenReturn("collection-uid");
    this.setUpOwner(sharer);
    Set<CollectionItem> parents = new HashSet<>(Arrays.asList(new CollectionItem[] { collection }));
    when(item.getParents()).thenReturn(parents);

    when(sharer.getUsername()).thenReturn(U_SHARER);
    when(sharee.getUsername()).thenReturn(U_SHAREE);
    when(userDao.getUser(U_SHARER)).thenReturn(sharer);
    when(userDao.getUser(U_SHAREE)).thenReturn(sharee);
}
 
Example #10
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void priniciapAndCredentialsAreTheSameAndSourceIpIsWithinList() {
    final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", REQUEST_SOURCE_IP,
            "192.168.1.3" };
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

    final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider(
            trustedIPAddresses);

    // test, should throw authentication exception
    final Authentication authenticate = underTestWithList.authenticate(token);
    assertThat(authenticate.isAuthenticated()).isTrue();
}
 
Example #11
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void setOperatorContext() {
    String user = "Operator";
    String fullName = "SLC Operator";
    List<String> roles = Arrays.asList(RoleInitializer.SLC_OPERATOR);

    Entity entity = Mockito.mock(Entity.class);
    Mockito.when(entity.getType()).thenReturn("admin-staff");
    Mockito.when(entity.getEntityId()).thenReturn(user);
    SLIPrincipal principal = buildPrincipal(user, fullName, DEFAULT_REALM_ID, roles, entity, ED_ORG_ID, new EdOrgContextRightsCache());
    principal.setRoles(roles);
    principal.setAdminRealmAuthenticated(true);
    setSecurityContext(principal, true);

    Right[] rights = new Right[] { Right.ADMIN_ACCESS, Right.SLC_APP_APPROVE };
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(SecurityContextHolder
            .getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext()
            .getAuthentication().getCredentials(), Arrays.asList(rights));

    LOG.debug("elevating rights to {}", Arrays.toString(rights));
    SecurityContextHolder.getContext().setAuthentication(token);
}
 
Example #12
Source File: PreAuthUserDetailsService.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
	String xAuthToken = (String) token.getPrincipal();
	UserDetails user = preAuthenticatedTokenCacheService.getFromCache(xAuthToken);

	if (user == null) {
           throw new UsernameNotFoundException("Pre authenticated token not found : " + xAuthToken);
       } else {
           if (log.isTraceEnabled()) {
               log.trace("Retrieved user from cache: " + user.getUsername());
           }

           // we want to update the expiration date on this key because the user is actively using it
           preAuthenticatedTokenCacheService.updateExpiration(xAuthToken);
       }

	return user;
}
 
Example #13
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
private void authenticate(String authToken) {
    if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
        log.debug("Header auth token: " + authToken);
    }

    if (StringUtils.isNotBlank(authToken)) {

        // set cached authenticated user back in the spring security context
        Authentication authentication = authenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

        if (log.isDebugEnabled()) {
            log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
        }
        SpringSecurityHelper.setAuthentication(authentication);

    }
}
 
Example #14
Source File: TrustedUserAuthenticationFilter.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * doFilter implementation for an HTTP request and response.
 *
 * @param request the HTTP servlet request.
 * @param response the HTTP servlet response.
 * @param chain the filter chain.
 *
 * @throws IOException if an I/O error occurs.
 * @throws ServletException if a servlet error occurs.
 */
public void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
    // Check if security is enabled
    // If security is not enabled, perform allow as trusted user.
    if (!securityHelper.isSecurityEnabled(request))
    {
        // If authentication is not there or is not of trusted user type.
        PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(request), "N/A");
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authResult = authenticationManager.authenticate(authRequest);

        // The authentication returned so it was successful.
        SecurityContextHolder.getContext().setAuthentication(authResult);
    }

    chain.doFilter(request, response);
}
 
Example #15
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void setLeaAdminContext() {
    String user = "LeaAdmin";
    String fullName = "LEA Admin";
    List<String> roles = Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR);

    Entity entity = Mockito.mock(Entity.class);
    Mockito.when(entity.getType()).thenReturn("admin-staff");
    Mockito.when(entity.getEntityId()).thenReturn(user);
    SLIPrincipal principal = buildPrincipal(user, fullName, DEFAULT_REALM_ID, roles, entity, null, null);
    principal.setExternalId("lea_admin");
    principal.setAdminRealmAuthenticated(true);
    setSecurityContext(principal, true);

    Right[] rights = new Right[] { Right.ADMIN_ACCESS, Right.EDORG_APP_AUTHZ };
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(SecurityContextHolder
            .getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext()
            .getAuthentication().getCredentials(), Arrays.asList(rights));

    LOG.debug("elevating rights to {}", Arrays.toString(rights));
    SecurityContextHolder.getContext().setAuthentication(token);
    SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT);
}
 
Example #16
Source File: HttpHeaderAuthenticationFilter.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the user based on the given request, and puts the user into the security context. Throws if authentication fails.
 *
 * @param servletRequest {@link HttpServletRequest} containing the user's request.
 */
private void authenticateUser(HttpServletRequest servletRequest)
{
    try
    {
        // Setup the authentication request and perform the authentication. Perform the authentication based on the fully built user.
        PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken =
            new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(servletRequest), "N/A");
        preAuthenticatedAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(servletRequest));
        Authentication authentication = authenticationManager.authenticate(preAuthenticatedAuthenticationToken);

        // The authentication returned so it was successful.
        successfulAuthentication(authentication);
    }
    catch (AuthenticationException e)
    {
        // An authentication exception was thrown so authentication failed.
        unsuccessfulAuthentication(servletRequest, e);

        // Throw an exception so we don't continue since there is some problem (e.g. user profile doesn't
        // exist for the logged in user or it couldn't be retrieved).
        throw e;
    }
}
 
Example #17
Source File: RightAccessValidatorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetContextualAuthoritiesNonStaff() {
    String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*";
    Entity princEntity = new MongoEntity(null, "RegularTeacher2", new HashMap<String,Object>(), new HashMap<String,Object>());
    SLIPrincipal principal = new SLIPrincipal();
    principal.setUserType(EntityNames.TEACHER);
    principal.setEntity(princEntity);
    PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS);
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    Entity entity = new MongoEntity("student", null, new HashMap<String,Object>(), new HashMap<String,Object>());

    Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false);

    Assert.assertEquals("Expected educator rights", EDU_AUTHS, auths);
}
 
Example #18
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void setSeaAdminContext() {
    String user = "LeaAdmin";
    String fullName = "LEA Admin";
    List<String> roles = Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR);

    Entity entity = Mockito.mock(Entity.class);
    Mockito.when(entity.getType()).thenReturn("admin-staff");
    Mockito.when(entity.getEntityId()).thenReturn(user);
    SLIPrincipal principal = buildPrincipal(user, fullName, DEFAULT_REALM_ID, roles, entity, ED_ORG_ID, new EdOrgContextRightsCache());
    principal.setExternalId("lea_admin");
    principal.setAdminRealmAuthenticated(true);
    setSecurityContext(principal, true);

    Right[] rights = new Right[] { Right.ADMIN_ACCESS, Right.EDORG_DELEGATE };
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(SecurityContextHolder
            .getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext()
            .getAuthentication().getCredentials(), Arrays.asList(rights));

    LOG.debug("elevating rights to {}", Arrays.toString(rights));
    SecurityContextHolder.getContext().setAuthentication(token);
    SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT);
}
 
Example #19
Source File: RightAccessValidatorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetContextualAuthoritiesNonStaffSelf() {
    String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*";
    Entity princEntity = new MongoEntity(null, "RegularTeacher3", new HashMap<String,Object>(), new HashMap<String,Object>());
    SLIPrincipal principal = new SLIPrincipal();
    principal.setEntity(princEntity);
    principal.setUserType(EntityNames.TEACHER);
    principal.setSelfRights(ADMIN_AUTHS);
    PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS);
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    Entity entity = new MongoEntity("teacher", null, new HashMap<String,Object>(), new HashMap<String,Object>());

    Collection<GrantedAuthority> auths = service.getContextualAuthorities(true, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false);

    Assert.assertEquals("Expected all rights", ALL_AUTHS, auths);
}
 
Example #20
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.")
public void priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching() {
    final String remoteAddress = "192.168.1.1";
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress);

    // test, should throw authentication exception

    try {
        underTestWithSourceIpCheck.authenticate(token);
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
 
Example #21
Source File: AbstractAuthenticatedController.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
protected void authenticate(StompHeaderAccessor accessor) {
    String authToken = accessor.getFirstNativeHeader(ServerConstants.X_AUTH_TOKEN);

    if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
        log.debug("Header auth token: " + authToken);
    }

    if (StringUtils.isNotBlank(authToken)) {

        // set cached authenticated user back in the spring security context
        Authentication authentication = preAuthAuthenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

        if (log.isDebugEnabled()) {
            log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
        }

        SpringSecurityHelper.setAuthentication(authentication);

    }
}
 
Example #22
Source File: AmqpControllerAuthenticationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests authentication message successfull")
public void successfullMessageAuthentication() {
    final MessageProperties messageProperties = createMessageProperties(null);
    final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, null, CONTROLLER_ID, null,
            FileResource.createFileResourceBySha1(SHA1));
    when(tenantConfigurationManagementMock.getConfigurationValue(
            eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class)))
                    .thenReturn(CONFIG_VALUE_TRUE);
    securityToken.putHeader(DmfTenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLER_ID);
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
            messageProperties);

    // test
    final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message);

    // verify
    final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage);
    assertThat(downloadResponse).isNotNull();
    assertThat(downloadResponse.getDownloadUrl()).isNotNull();
    assertThat(downloadResponse.getResponseCode()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication().getClass().getName())
            .isEqualTo(PreAuthenticatedAuthenticationToken.class.getName());

}
 
Example #23
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source Ip is matching the allowed remote IP address.")
public void priniciapAndCredentialsAreTheSameAndSourceIpIsTrusted() {
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

    // test, should throw authentication exception
    final Authentication authenticate = underTestWithSourceIpCheck.authenticate(token);
    assertThat(authenticate.isAuthenticated()).isTrue();
}
 
Example #24
Source File: SpringSecurityUtils.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
/**
 * Save user details to security context.
 *
 * @param userDetails user details
 * @param request     request
 */
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) {
  PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
      userDetails,
      userDetails.getPassword(), userDetails.getAuthorities());

  if (request != null) {
    authentication.setDetails(new WebAuthenticationDetails(request));
  }

  SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example #25
Source File: AmqpControllerAuthenticationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests authentication message successfull with targetId intead of controllerId provided and artifactId instead of SHA1.")
public void successfullMessageAuthenticationWithTargetIdAndArtifactId() {
    final MessageProperties messageProperties = createMessageProperties(null);
    final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, null, null, TARGET_ID,
            FileResource.createFileResourceByArtifactId(ARTIFACT_ID));
    when(tenantConfigurationManagementMock.getConfigurationValue(
            eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class)))
                    .thenReturn(CONFIG_VALUE_TRUE);
    securityToken.putHeader(DmfTenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLER_ID);
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
            messageProperties);

    // test
    final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message);

    // verify
    final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage);
    assertThat(downloadResponse).isNotNull();
    assertThat(downloadResponse.getDownloadUrl()).isNotNull();
    assertThat(downloadResponse.getResponseCode()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication().getClass().getName())
            .isEqualTo(PreAuthenticatedAuthenticationToken.class.getName());

}
 
Example #26
Source File: SpringSecurityUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * 将UserDetails保存到Security Context.
 * 
 * @param userDetails
 *            已初始化好的用户信息.
 * @param request
 *            用于获取用户IP地址信息,可为Null.
 */
public static void saveUserDetailsToContext(UserDetails userDetails,
        HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
            userDetails, userDetails.getPassword(),
            userDetails.getAuthorities());

    if (request != null) {
        authentication.setDetails(new WebAuthenticationDetails(request));
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example #27
Source File: STSPreAuthAuthenticationProvider.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) {
    // We only handle PreAuthenticatedAuthenticationTokens
    if (!(authentication instanceof PreAuthenticatedAuthenticationToken)) {
        return null;
    }

    Bus cxfBus = getBus();
    IdpSTSClient sts = new IdpSTSClient(cxfBus);
    sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
    if (tokenType != null && tokenType.length() > 0) {
        sts.setTokenType(tokenType);
    } else {
        sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
    }
    sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
    sts.setWsdlLocation(getWsdlLocation());
    sts.setServiceQName(new QName(namespace, wsdlService));
    sts.setEndpointQName(new QName(namespace, wsdlEndpoint));

    sts.getProperties().putAll(properties);
    if (use200502Namespace) {
        sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
    }

    if (lifetime != null) {
        sts.setEnableLifetime(true);
        sts.setTtl(lifetime.intValue());
    }

    return handlePreAuthenticated((PreAuthenticatedAuthenticationToken)authentication, sts);
}
 
Example #28
Source File: SecurityContextInjector.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public SLIPrincipal setOauthSecurityContext(SLIPrincipal principal, boolean  isAdminRealm) {
    String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*";
    LOG.debug("assembling authentication token");
    PreAuthenticatedAuthenticationToken authenticationToken = getAuthenticationToken(token, principal, isAdminRealm);
    OAuth2Authentication oauth = new OAuth2Authentication(new ClientToken("clientId", "clientSecret", Collections.singleton("scope")), authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(oauth);
    SecurityUtil.getSLIPrincipal().setAuthorizingEdOrgs(new HashSet<String>(Arrays.asList(principal.getEdOrg())));
    return  principal;
}
 
Example #29
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Bean
public ChannelInterceptorAdapter sessionContextChannelInterceptorAdapter() {
    return new ChannelInterceptorAdapter() {
        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            StompCommand command = accessor.getCommand();

            if (log.isDebugEnabled() && command != null) {
                log.debug("StompCommand: " + command.toString());
            }

            String authToken = accessor.getFirstNativeHeader(ServerConstants.X_AUTH_TOKEN);

            if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
                log.debug("Header auth token: " + authToken);
            }

            if (StringUtils.isNotBlank(authToken)) {

                // set cached authenticated user back in the spring security context
                Authentication authentication = preAuthAuthenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

                if (log.isDebugEnabled()) {
                    log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
                }
                SpringSecurityHelper.setAuthentication(authentication);

            }
            return super.preSend(message, channel);
        }
    };
}
 
Example #30
Source File: ConfigAwarePreAuthenticationFilter.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean principalChanged(final HttpServletRequest request, final Authentication currentAuthentication) {
    logger.debug("Current authentication class: " + currentAuthentication.getClass().getSimpleName());
    logger.debug("Current principal class:" + currentAuthentication.getPrincipal().getClass().getSimpleName());
    if (currentAuthentication instanceof PreAuthenticatedAuthenticationToken &&
        (supportedPrincipalClass == null ||
        currentAuthentication.getPrincipal().getClass().equals(supportedPrincipalClass))) {
        logger.debug("Current authentication and principal are supported, continuing verification");
        return super.principalChanged(request, currentAuthentication);
    } else {
        logger.debug("Current authentication or principal class is not supported, skipping verification");
        return false;
    }
}