Java 类org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken 实例源码

项目:syndesis    文件:UserHandlerTest.java   
@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");
}
项目:syndesis    文件:UserHandlerTest.java   
@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();
}
项目:azure-spring-boot    文件:TodolistController.java   
/**
 * 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);
    }

}
项目:SpringBootStudy    文件:JsonWebTokenAuthenticationProvider.java   
@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;
}
项目:todolist    文件:ApiAuthenticationUserDetailsService.java   
@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;
}
项目:fiat    文件:FiatAuthenticationFilter.java   
@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);
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
@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;
}
项目:engerek    文件:MidPointAuthenticationProvider.java   
@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;
}
项目:IdentityRegistry    文件:AccessControlUtil.java   
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;
}
项目:syndesis-rest    文件:UserHandlerTest.java   
@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");
}
项目:syndesis-rest    文件:UserHandlerTest.java   
@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();
}
项目:jwt-with-spring    文件:JwtAuthenticationTokenFilter.java   
@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);
}
项目:herd    文件:HttpHeaderAuthenticationFilter.java   
/**
 * 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;
    }
}
项目:herd    文件:TrustedUserAuthenticationFilter.java   
/**
 * 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);
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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) {

    }

}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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) {

    }
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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();
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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) {

    }
}
项目:hawkbit    文件:AmqpControllerAuthentication.java   
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());
}
项目:trivia-microservices    文件:JsonWebTokenAuthenticationProvider.java   
@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;
}
项目:webanno    文件:SpringAuthenticatedWebSession.java   
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);
    }
}
项目:CAPortal    文件:CaX509JdbcPreAuthUserDetails.java   
/**
 * Query CA database for user with given X509Certificate and load their roles.  
 * If user is not found, throw a UsernameNotFoundException. 
 * 
 * @param token Must be castable to a {@link java.security.cert.X509Certificate} object  
 * @return UserDetails (never null)  
 */
@Override
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) {
    // http://stackoverflow.com/questions/14563397/spring-security-x-509-authentication-without-user-service
    X509Certificate certificate = (X509Certificate) token.getCredentials();
    String dn = certificate.getSubjectDN().toString();
    // Convert provided DN to rfc2253 style (commas with no spaces) 
    // from: "CN=david meredith, L=DL, OU=CLRC, O=eScience, C=UK"
    // to: "CN=david meredith,L=DL,OU=CLRC,O=eScience,C=UK"
    dn = dn.replaceAll(", ", ",");
    BigInteger serial = certificate.getSerialNumber();
    log.info("Auth request for dn: [" + dn + "] serial: [" + serial.toString() + "]");
    CertificateRow cr = this.jdbcCertDao.findById(serial.longValue());

    if (cr != null) {
        List<GrantedAuthority> auths = this.securityContextService.getGrantedAuthorities(cr);  
        return new CaUser(dn, true, true, true, true, auths, cr);
    }
    throw new UsernameNotFoundException("User Not found [" + dn + "] ["+serial.toString()+"]");
}
项目:cosmo    文件:CosmoSecurityManagerImpl.java   
/**
 * Provide a <code>CosmoSecurityContext</code> representing a
 * Cosmo user previously authenticated by the Cosmo security
 * system.
 */
public CosmoSecurityContext getSecurityContext()
    throws CosmoSecurityException {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authen = context.getAuthentication();
    if (authen == null) {
        throw new CosmoSecurityException("no Authentication found in " +
                                         "SecurityContext");
    }

    if (authen instanceof PreAuthenticatedAuthenticationToken) {
        User user = userService.getUser((String) authen.getPrincipal());
        return new CosmoSecurityContextImpl(authen, tickets.get(), user);
    }


    return createSecurityContext(authen);
}
项目:cosmo    文件:SecurityAdviceTestTwo.java   
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    this.advice = new SecurityAdvice();
    this.advice.setContentDao(contentDao);
    this.advice.setUserDao(userDao);
    this.advice.setSecurityManager(securityManager);
    this.advice.init();
    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);
}
项目:itpkg    文件:AuthenticationFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;


    String ticket = getTicket(req);
    if (ticket != null) {
        try {
            Authentication reqAuth = new PreAuthenticatedAuthenticationToken(ticket, null);
            Authentication respAuth = authenticationManager.authenticate(reqAuth);

            if (respAuth != null && respAuth.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(respAuth);
            }

        } catch (AuthenticationException e) {
            logger.error("auth failed", e);
            SecurityContextHolder.clearContext();
            //resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    chain.doFilter(request, response);
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@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;
}
项目:midpoint    文件:MidPointAuthenticationProvider.java   
@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;
}
项目:codekvast    文件:SecurityServiceImpl.java   
private Authentication toAuthentication(String token) throws AuthenticationException {

        if (token == null || settings.isDemoMode()) {
            return null;
        }

        int pos = token.startsWith(BEARER_) ? BEARER_.length() : 0;

        try {
            Jws<Claims> claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token.substring(pos));

            return new PreAuthenticatedAuthenticationToken(
                Long.valueOf(claims.getBody().getSubject()),
                WebappCredentials.builder()
                                 .externalId(claims.getBody().getId())
                                 .customerName(claims.getBody().get(JWT_CLAIM_CUSTOMER_NAME, String.class))
                                 .email(claims.getBody().get(JWT_CLAIM_EMAIL, String.class))
                                 .source(claims.getBody().get(JWT_CLAIM_SOURCE, String.class))
                                 .build(),
                USER_AUTHORITY);
        } catch (Exception e) {
            logger.debug("Failed to authenticate token: " + e);
            return null;
        }
    }
项目:play-oauth2    文件:SecurityAuthenticationFilter.java   
@Override
public Promise<Result> apply(Request request, Method method, Context context, Action<?> action)
    throws Throwable {
  String token = getAuthorizationToken(request);
  if (token == null) {
    token = request.getQueryString(OAuth2AccessToken.ACCESS_TOKEN);
  }
  if (token == null) {
    logger.info("Authentication skipped");
  } else {
    Authentication authRequest = new PreAuthenticatedAuthenticationToken(token, "");
    Authentication authResult = oauth2AuthenticationManager.authenticate(authRequest);
    SecurityContextHolder.getContext().setAuthentication(authResult);
    logger.info("Authenticated successfully");
  }
  return action.call(context);
}
项目:bearchoke    文件:PreAuthUserDetailsService.java   
@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;
}
项目:bearchoke    文件:WebSocketConfig.java   
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);

    }
}
项目:bearchoke    文件:AbstractAuthenticatedController.java   
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);

    }
}
项目:netcare-healthplan    文件:UserDetailsServiceImpl.java   
@Override
public ServiceResult<Boolean> saveUserData(String firstName, String surName) {
    final UserEntity user = this.getCurrentUser();

    getLog().info("Updating user data for user {}", user.getUsername());

    user.setFirstName(firstName);
    user.setSurName(surName);

    final UserBaseView ubv;
    if (user.isCareActor()) {
        ubv = CareActorBaseViewImpl.newFromEntity((CareActorEntity) user);
    } else {
        ubv = PatientBaseViewImpl.newFromEntity((PatientEntity) user);
    }

    /*
     * Refresh security context
     */
    getLog().debug("Refreshing security context with updated firstname/surname");
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(ubv, "n/a"));

    return ServiceResultImpl.createSuccessResult(Boolean.TRUE, new GenericSuccessMessage());
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@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;
}
项目:midpoint    文件:MidPointAuthenticationProvider.java   
@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;
}
项目:ngrinder-siteminder-sso    文件:SiteMinderFilter.java   
@Override
public void doFilter(final ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String userId = httpServletRequest.getHeader(userIdHeader);
    if (authentication == null && StringUtils.isNotEmpty(userId)) {
        userId = userId.toLowerCase();
        LOGGER.info("[NOTICE][SSO] {} is accessing through SSO", userId);
        PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
            userId, "");
        token.setDetails(createDetails(httpServletRequest, userId));
        threadStorage.set(createEmpInfoFrom(httpServletRequest));
        Authentication authenticate = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
    }
    chain.doFilter(request, response);
}
项目:secure-data-service    文件:SecuritySessionResource.java   
/**
 * 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;
}
项目:secure-data-service    文件:RightAccessValidatorTest.java   
@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);
}