当前位置: 首页>>代码示例>>Java>>正文


Java PreAuthenticatedAuthenticationToken类代码示例

本文整理汇总了Java中org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken的典型用法代码示例。如果您正苦于以下问题:Java PreAuthenticatedAuthenticationToken类的具体用法?Java PreAuthenticatedAuthenticationToken怎么用?Java PreAuthenticatedAuthenticationToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PreAuthenticatedAuthenticationToken类属于org.springframework.security.web.authentication.preauth包,在下文中一共展示了PreAuthenticatedAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: successfulWhoAmI

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Test
public void successfulWhoAmI() {
    openShiftServer.expect()
        .get().withPath("/oapi/v1/users/~")
        .andReturn(
            200,
            new UserBuilder().withFullName("Test User").withNewMetadata().withName("testuser").and().build()
        ).once();

    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("testuser", "doesn'tmatter"));

    UserHandler userHandler = new UserHandler(null, new OpenShiftServiceImpl(openShiftServer.getOpenshiftClient(), null));
    User user = userHandler.whoAmI();
    Assertions.assertThat(user).isNotNull();
    Assertions.assertThat(user.getUsername()).isEqualTo("testuser");
    Assertions.assertThat(user.getFullName()).isNotEmpty().hasValue("Test User");
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:18,代码来源:UserHandlerTest.java

示例2: successfulWhoAmIWithoutFullName

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Test
public void successfulWhoAmIWithoutFullName() {
    openShiftServer.expect()
        .get().withPath("/oapi/v1/users/~")
        .andReturn(
            200,
            new UserBuilder().withNewMetadata().withName("testuser").and().build()
        ).once();

    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("testuser", "doesn'tmatter"));

    UserHandler userHandler = new UserHandler(null, new OpenShiftServiceImpl(openShiftServer.getOpenshiftClient(), null));
    User user = userHandler.whoAmI();
    Assertions.assertThat(user).isNotNull();
    Assertions.assertThat(user.getUsername()).isEqualTo("testuser");
    Assertions.assertThat(user.getFullName()).isEmpty();
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:18,代码来源:UserHandlerTest.java

示例3: deleteTodoItem

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
/**
 * HTTP DELETE
 */
@RequestMapping(value = "/api/todolist/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteTodoItem(@PathVariable("id") int id,
                                             PreAuthenticatedAuthenticationToken authToken) {
    final UserPrincipal current = (UserPrincipal) authToken.getPrincipal();

    if (current.isMemberOf(
            new UserGroup("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "group1"))) {
        final List<TodoItem> find = todoList.stream().filter(i -> i.getID() == id).collect(Collectors.toList());
        if (!find.isEmpty()) {
            todoList.remove(todoList.indexOf(find.get(0)));
            return new ResponseEntity<>("OK", HttpStatus.OK);
        }
        return new ResponseEntity<>("Entity not found", HttpStatus.OK);
    } else {
        return new ResponseEntity<>("Access is denied", HttpStatus.OK);
    }

}
 
开发者ID:Microsoft,项目名称:azure-spring-boot,代码行数:22,代码来源:TodolistController.java

示例4: loadUserDetails

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws AuthenticationException {
	Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
	String credentials = (String)token.getCredentials();
	for(String credential : StringUtils.split(credentials, ";")) {
		if(mappingGroupesRoles != null && mappingGroupesRoles.containsKey(credential)){ 
			authorities.add(new SimpleGrantedAuthority(mappingGroupesRoles.get(credential)));
		}
	}
	for(String roleFromLdap : ldapGroup2UserRoleService.getRoles(token.getName())) {
		authorities.add(new SimpleGrantedAuthority(roleFromLdap));
	}
	log.info("Shib & Ldap Credentials for " + token.getName() + " -> " + authorities);
	return createUserDetails(token, authorities);
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:15,代码来源:ShibAuthenticatedUserDetailsService.java

示例5: authenticate

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication authenticationUser = null;
    // 只处理 PreAuthenticatedAuthenticationToken
    if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class)
            && authentication.getPrincipal() != null) {
        String tokenHeader = (String) authentication.getPrincipal();
        UserDetails userDetails = parseToken(tokenHeader);
        if (userDetails != null) {
            authenticationUser = new JsonWebTokenAuthentication(userDetails, tokenHeader);
        }
    } else {
        // 已经有 JsonWebTokenAuthentication
        authenticationUser = authentication;
    }
    return authenticationUser;
}
 
开发者ID:jeikerxiao,项目名称:SpringBootStudy,代码行数:18,代码来源:JsonWebTokenAuthenticationProvider.java

示例6: loadUserDetails

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@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;
}
 
开发者ID:nonocast,项目名称:todolist,代码行数:22,代码来源:ApiAuthenticationUserDetailsService.java

示例7: doFilter

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  Authentication auth = AuthenticatedRequest
      .getSpinnakerUser()
      .map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username,
                                                                                null,
                                                                                new ArrayList<>()))
      .orElseGet(() -> new AnonymousAuthenticationToken(
          "anonymous",
          "anonymous",
          AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")
      ));

  val ctx = SecurityContextHolder.createEmptyContext();
  ctx.setAuthentication(auth);
  SecurityContextHolder.setContext(ctx);
  log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString());
  chain.doFilter(request, response);
}
 
开发者ID:spinnaker,项目名称:fiat,代码行数:20,代码来源:FiatAuthenticationFilter.java

示例8: authenticateUserPreAuthenticated

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv,
		String enteredUsername) {
	
	MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
	
	// Authorizations
	if (!hasAnyAuthorization(principal)) {
		recordAuthenticationFailure(principal, connEnv, "no authorizations");
		throw new AccessDeniedException("web.security.provider.access.denied");
	}
	
	PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
	
	recordAuthenticationSuccess(principal, connEnv);
	
	return token;
}
 
开发者ID:Pardus-Engerek,项目名称:engerek,代码行数:19,代码来源:AuthenticationEvaluatorImpl.java

示例9: authenticate

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@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;
}
 
开发者ID:Pardus-Engerek,项目名称:engerek,代码行数:26,代码来源:MidPointAuthenticationProvider.java

示例10: isUserSync

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
public static boolean isUserSync(String userSyncMRN, String userSyncO, String userSyncOU, String userSyncC) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof PreAuthenticatedAuthenticationToken) {
        log.debug("Certificate authentication of user sync'er in process");
        // Certificate authentication
        PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) auth;
        // Check that the Organization name of the accessed organization and the organization in the certificate is equal
        InetOrgPerson person = ((InetOrgPerson) token.getPrincipal());
        if (userSyncMRN.equalsIgnoreCase(person.getUid()) && userSyncO.equalsIgnoreCase(person.getO())
                // Hack alert! There is no country property in this type, so we misuse PostalAddress...
                && userSyncOU.equals(person.getOu()) && userSyncC.equals(person.getPostalAddress())) {
            log.debug("User sync'er accepted!");
            return true;
        }
        log.debug("This was not the user-sync'er! " + userSyncMRN + "~" + person.getUid() + ", " + userSyncO + "~"
                + person.getO() + ", " + userSyncOU + "~" + person.getOu() + ", " + userSyncC + "~" + person.getPostalAddress());
    }
    return false;
}
 
开发者ID:MaritimeConnectivityPlatform,项目名称:IdentityRegistry,代码行数:20,代码来源:AccessControlUtil.java

示例11: doFilter

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String header = httpRequest.getHeader("Authorization");
    final SecurityContext context = SecurityContextHolder.getContext();
    if (header != null && context.getAuthentication() == null) {
        final String tokenStr = header.substring("Bearer ".length());
        final JwtToken token = jwtTokenCodec.decodeToken(tokenStr);
        if (!token.isExpired()) {
            final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(token, "n/a", token.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            context.setAuthentication(authentication);
        }
    }
    chain.doFilter(request, response);
}
 
开发者ID:nidi3,项目名称:jwt-with-spring,代码行数:17,代码来源:JwtAuthenticationTokenFilter.java

示例12: authenticateUser

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:29,代码来源:HttpHeaderAuthenticationFilter.java

示例13: doHttpFilter

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:28,代码来源:TrustedUserAuthenticationFilter.java

示例14: principalAndCredentialsNotTheSameThrowsAuthenticationException

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@Test
@Description("Testing in case the containing controllerId in the URI request path does not accord with the controllerId in the request header.")
public void principalAndCredentialsNotTheSameThrowsAuthenticationException() {
    final String principal = "controllerIdURL";
    final String credentials = "controllerIdHeader";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    // test, should throw authentication exception
    try {
        underTestWithoutSourceIpCheck.authenticate(token);
        fail("Should not work with wrong credentials");
    } catch (final BadCredentialsException e) {

    }

}
 
开发者ID:eclipse,项目名称:hawkbit,代码行数:19,代码来源:PreAuthTokenSourceTrustAuthenticationProviderTest.java

示例15: priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching

import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; //导入依赖的package包/类
@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) {

    }
}
 
开发者ID:eclipse,项目名称:hawkbit,代码行数:22,代码来源:PreAuthTokenSourceTrustAuthenticationProviderTest.java


注:本文中的org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。