當前位置: 首頁>>代碼示例>>Java>>正文


Java AuthenticationException類代碼示例

本文整理匯總了Java中javax.naming.AuthenticationException的典型用法代碼示例。如果您正苦於以下問題:Java AuthenticationException類的具體用法?Java AuthenticationException怎麽用?Java AuthenticationException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AuthenticationException類屬於javax.naming包,在下文中一共展示了AuthenticationException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: authenticate

import javax.naming.AuthenticationException; //導入依賴的package包/類
/**
 * {@inheritDoc}
 */
public Principal authenticate() throws AuthenticationException {
    final KeyManager keyManager = KeyManager.getInstance();
    if (bearer != null) {
        final JsonWebToken jwt = new JsonWebToken(keyManager.getSecretKey());
        final boolean isValid = jwt.validateToken(bearer);
        if (isValid) {
            try (AlpineQueryManager qm = new AlpineQueryManager()) {
                if (jwt.getSubject() == null || jwt.getExpiration() == null) {
                    throw new AuthenticationException("Token does not contain a valid subject or expiration");
                }
                final ManagedUser managedUser = qm.getManagedUser(jwt.getSubject());
                if (managedUser != null) {
                    return managedUser;
                }
                final LdapUser ldapUser =  qm.getLdapUser(jwt.getSubject());
                if (ldapUser != null) {
                    return ldapUser;
                }
            }
        }
    }
    return null;
}
 
開發者ID:stevespringett,項目名稱:Alpine,代碼行數:27,代碼來源:JwtAuthenticationService.java

示例2: checkAuth

import javax.naming.AuthenticationException; //導入依賴的package包/類
/**
 * @param response is the first line read after the user logs in. If it fails, close the socket, writer, and reader.
 * @throws AuthenticationException Invalid oauth key.
 * @throws IOException
 */
private void checkAuth(final String response) throws AuthenticationException, IOException {
    if (response.endsWith(Constants.AUTH_FAILED)) {
        closeAll();
        throw new AuthenticationException(Constants.AUTH_FAILED);
    }

    if (response.endsWith(Constants.BAD_AUTH_FORMAT)) {
        closeAll();
        throw new AuthenticationException(Constants.BAD_AUTH_FORMAT);
    }

    if (!response.endsWith(Constants.VALID_AUTH)) {
        closeAll();
        throw new AuthenticationException(Constants.AUTH_FAILED_GENERIC);
    }
}
 
開發者ID:agapic,項目名稱:Twitch-Streamer,代碼行數:22,代碼來源:IRC.java

示例3: authenticateHttpRequest

import javax.naming.AuthenticationException; //導入依賴的package包/類
public String authenticateHttpRequest(HttpServletRequest request) throws AuthenticationException {
    // Try to validate with any configured provider
    AuthenticationDataSource authData = new AuthenticationDataHttps(request);
    for (AuthenticationProvider provider : providers.values()) {
        try {
            return provider.authenticate(authData);
        } catch (AuthenticationException e) {
            // Ignore the exception because we don't know which authentication method is expected here.
        }
    }

    // No authentication provided
    if (!providers.isEmpty()) {
        if (StringUtils.isNotBlank(anonymousUserRole)) {
            return anonymousUserRole;
        }
        // If at least a provider was configured, then the authentication needs to be provider
        throw new AuthenticationException("Authentication required");
    } else {
        // No authentication required
        return "<none>";
    }
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:24,代碼來源:AuthenticationService.java

示例4: clientAppId

import javax.naming.AuthenticationException; //導入依賴的package包/類
/**
 * Gets a caller id (IP + role)
 *
 * @return the web service caller identification
 */
public String clientAppId() {
    if (isBlank(clientId)) {
        try {
            clientId = service().getAuthenticationService().authenticateHttpRequest(httpRequest);
        } catch (AuthenticationException e) {
            if (service().getConfig().isAuthenticationEnabled()) {
                throw new RestException(Status.UNAUTHORIZED, "Failed to get clientId from request");
            }
        }

        if (isBlank(clientId) && service().getConfig().isAuthenticationEnabled()) {
            throw new RestException(Status.UNAUTHORIZED, "Failed to get auth data from the request");
        }
    }
    return clientId;
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:22,代碼來源:WebSocketWebResource.java

示例5: doFilter

import javax.naming.AuthenticationException; //導入依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {
        String role = authenticationService.authenticateHttpRequest((HttpServletRequest) request);
        request.setAttribute(AuthenticatedRoleAttributeName, role);

        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] Authenticated HTTP request with role {}", request.getRemoteAddr(), role);
        }
    } catch (AuthenticationException e) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
        LOG.warn("[{}] Failed to authenticate HTTP request: {}", request.getRemoteAddr(), e.getMessage());
        return;
    }

    chain.doFilter(request, response);
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:21,代碼來源:AuthenticationFilter.java

示例6: testConnectCommandWithAuthenticationNegative

import javax.naming.AuthenticationException; //導入依賴的package包/類
@Test(timeOut = 30000)
public void testConnectCommandWithAuthenticationNegative() throws Exception {
    AuthenticationException e = new AuthenticationException();
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    doReturn(authenticationService).when(brokerService).getAuthenticationService();
    doThrow(e).when(authenticationService).authenticate(new AuthenticationDataCommand(Mockito.anyString()),
            Mockito.anyString());
    doReturn(true).when(brokerService).isAuthenticationEnabled();

    resetChannel();
    assertTrue(channel.isActive());
    assertEquals(serverCnx.getState(), State.Start);

    // test server response to CONNECT
    ByteBuf clientCommand = Commands.newConnect("none", "", null);
    channel.writeInbound(clientCommand);

    assertEquals(serverCnx.getState(), State.Start);
    assertTrue(getResponse() instanceof CommandError);
    channel.finish();
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:22,代碼來源:ServerCnxTest.java

示例7: testAuthenticateUnsignedToken

import javax.naming.AuthenticationException; //導入依賴的package包/類
@Test
public void testAuthenticateUnsignedToken() throws Exception {

    List<String> roles = new ArrayList<String>() {
        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build();
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getUnsignedToken(),
            new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Unsigned token should not be authenticated");
    } catch (AuthenticationException e) {
        // OK, expected
    }
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:19,代碼來源:AuthenticationProviderAthenzTest.java

示例8: testAuthenticateSignedTokenWithDifferentDomain

import javax.naming.AuthenticationException; //導入依賴的package包/類
@Test
public void testAuthenticateSignedTokenWithDifferentDomain() throws Exception {

    List<String> roles = new ArrayList<String>() {
        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "invalid", roles).principal("test_app").build();
    String privateKey = new String(Files.readAllBytes(Paths.get("./src/test/resources/zts_private.pem")));
    token.sign(privateKey);
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getSignedToken(),
            new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Token which has different domain should not be authenticated");
    } catch (AuthenticationException e) {
        // OK, expected
    }
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:21,代碼來源:AuthenticationProviderAthenzTest.java

示例9: validateAuthenticationInfo

import javax.naming.AuthenticationException; //導入依賴的package包/類
/**
 * Validates the configuration in the JNDI <code>environment</code> settings and throws an exception if a problem
 * exists.
 * <p/>
 * This implementation will throw a {@link AuthenticationException} if the authentication mechanism is set to
 * 'simple', the principal is non-empty, and the credentials are empty (as per
 * <a href="http://tools.ietf.org/html/rfc4513#section-5.1.2">rfc4513 section-5.1.2</a>).
 *
 * @param environment the JNDI environment settings to be validated
 * @throws AuthenticationException if a configuration problem is detected
 */
protected void validateAuthenticationInfo(Hashtable<String, Object> environment)
    throws AuthenticationException
{
    // validate when using Simple auth both principal and credentials are set
    if(SIMPLE_AUTHENTICATION_MECHANISM_NAME.equals(environment.get(Context.SECURITY_AUTHENTICATION))) {

        // only validate credentials if we have a non-empty principal
        if( environment.get(Context.SECURITY_PRINCIPAL) != null &&
            StringUtils.hasText( String.valueOf( environment.get(Context.SECURITY_PRINCIPAL) ))) {

            Object credentials = environment.get(Context.SECURITY_CREDENTIALS);

            // from the FAQ, we need to check for empty credentials:
            // http://docs.oracle.com/javase/tutorial/jndi/ldap/faq.html
            if( credentials == null ||
                (credentials instanceof byte[] && ((byte[])credentials).length <= 0) || // empty byte[]
                (credentials instanceof char[] && ((char[])credentials).length <= 0) || // empty char[]
                (String.class.isInstance(credentials) && !StringUtils.hasText(String.valueOf(credentials)))) {

                throw new javax.naming.AuthenticationException("LDAP Simple authentication requires both a "
                                                                   + "principal and credentials.");
            }
        }
    }
}
 
開發者ID:xuegongzi,項目名稱:rabbitframework,代碼行數:37,代碼來源:JndiLdapContextFactory.java

示例10: validateAuthenticationInfo

import javax.naming.AuthenticationException; //導入依賴的package包/類
/**
 * Validates the configuration in the JNDI <code>environment</code> settings and throws an exception if a problem
 * exists.
 * <p/>
 * This implementation will throw a {@link AuthenticationException} if the authentication mechanism is set to
 * 'simple', the principal is non-empty, and the credentials are empty (as per
 * <a href="http://tools.ietf.org/html/rfc4513#section-5.1.2">rfc4513 section-5.1.2</a>).
 *
 * @param environment the JNDI environment settings to be validated
 * @throws AuthenticationException if a configuration problem is detected
 */
private void validateAuthenticationInfo(Hashtable<String, Object> environment)
    throws AuthenticationException
{
    // validate when using Simple auth both principal and credentials are set
    if(SIMPLE_AUTHENTICATION_MECHANISM_NAME.equals(environment.get(Context.SECURITY_AUTHENTICATION))) {

        // only validate credentials if we have a non-empty principal
        if( environment.get(Context.SECURITY_PRINCIPAL) != null &&
            StringUtils.hasText( String.valueOf( environment.get(Context.SECURITY_PRINCIPAL) ))) {

            Object credentials = environment.get(Context.SECURITY_CREDENTIALS);

            // from the FAQ, we need to check for empty credentials:
            // http://docs.oracle.com/javase/tutorial/jndi/ldap/faq.html
            if( credentials == null ||
                (credentials instanceof byte[] && ((byte[])credentials).length <= 0) || // empty byte[]
                (credentials instanceof char[] && ((char[])credentials).length <= 0) || // empty char[]
                (String.class.isInstance(credentials) && !StringUtils.hasText(String.valueOf(credentials)))) {

                throw new javax.naming.AuthenticationException("LDAP Simple authentication requires both a "
                                                                   + "principal and credentials.");
            }
        }
    }
}
 
開發者ID:xuegongzi,項目名稱:rabbitframework,代碼行數:37,代碼來源:DefaultLdapContextFactory.java

示例11: getRoles

import javax.naming.AuthenticationException; //導入依賴的package包/類
private Set<String> getRoles(PrincipalCollection principals, 
      final LdapContextFactory ldapContextFactory)
    throws NamingException {
  final String username = (String) getAvailablePrincipal(principals);

  LdapContext systemLdapCtx = null;
  try {
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    return rolesFor(principals, username, systemLdapCtx,
      ldapContextFactory, SecurityUtils.getSubject().getSession());
  } catch (AuthenticationException ae) {
    ae.printStackTrace();
    return Collections.emptySet();
  } finally {
    LdapUtils.closeContext(systemLdapCtx);
  }
}
 
開發者ID:apache,項目名稱:zeppelin,代碼行數:18,代碼來源:LdapRealm.java

示例12: authenticateAndReturnPermittedGroups

import javax.naming.AuthenticationException; //導入依賴的package包/類
public Optional<User> authenticateAndReturnPermittedGroups(BasicCredentials credentials) throws io.dropwizard.auth.AuthenticationException {
    final String sanitizedUsername = sanitizeEntity(credentials.getUsername());
    try {
        try (AutoclosingLdapContext context = buildContext(sanitizedUsername, credentials.getPassword())) {
            Set<String> groupMemberships = getGroupMembershipsIntersectingWithRestrictedGroups(context, sanitizedUsername);
            if (!groupMemberships.isEmpty()) {
                return Optional.of(new User(sanitizedUsername, groupMemberships));
            }
        }
    } catch (AuthenticationException ae) {
        LOG.debug("{} failed to authenticate. {}", sanitizedUsername, ae);
    } catch (IOException | NamingException err) {
        throw new io.dropwizard.auth.AuthenticationException(String.format("LDAP Authentication failure (username: %s)",
                sanitizedUsername), err);
    }
    return Optional.empty();
}
 
開發者ID:yammer,項目名稱:dropwizard-auth-ldap,代碼行數:18,代碼來源:LdapAuthenticator.java

示例13: authenticate

import javax.naming.AuthenticationException; //導入依賴的package包/類
public void authenticate(final String userID, final String psswrd) throws AuthenticationException {

        final AuthenticationRequest req = new AuthenticationRequest(String.class.cast(env.get("openejb.authentication.realmName")), userID, psswrd);

        final AuthenticationResponse res;
        try {
            res = requestAuthorization(req);
        } catch (RemoteException e) {
            throw new AuthenticationException(e.getLocalizedMessage());
        }

        switch (res.getResponseCode()) {
            case ResponseCodes.AUTH_GRANTED:
                client = res.getIdentity();
                break;
            case ResponseCodes.AUTH_REDIRECT:
                client = res.getIdentity();
                server = res.getServer();
                break;
            case ResponseCodes.AUTH_DENIED:
                throw (AuthenticationException) new AuthenticationException("This principle is not authorized.").initCause(res.getDeniedCause());
        }
    }
 
開發者ID:apache,項目名稱:tomee,代碼行數:24,代碼來源:JNDIContext.java

示例14: logout

import javax.naming.AuthenticationException; //導入依賴的package包/類
private void logout() throws AuthenticationException {
    final LogoutRequest request = new LogoutRequest(client.getClientIdentity());

    final LogoutResponse response;
    try {
        response = LogoutResponse.class.cast(Client.request(request, new LogoutResponse(), server));
    } catch (final RemoteException e) {
        throw new AuthenticationException(e.getLocalizedMessage());
    }

    switch (response.getResponseCode()) {
        case ResponseCodes.AUTH_DENIED:
            throw AuthenticationException.class.cast(new AuthenticationException("Can't logout").initCause(response.getDeniedCause()));
        case ResponseCodes.LOGOUT_SUCCESS:
        default:
    }
}
 
開發者ID:apache,項目名稱:tomee,代碼行數:18,代碼來源:JNDIContext.java

示例15: login

import javax.naming.AuthenticationException; //導入依賴的package包/類
private void login() throws AuthenticationException {
    final String user = (String) properties.get(Context.SECURITY_PRINCIPAL);
    final String pass = (String) properties.get(Context.SECURITY_CREDENTIALS);
    final String realmName = (String) properties.get("openejb.authentication.realmName");

    if (user != null && pass != null) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Logging in: " + user);
            }
            final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
            if (realmName == null) {
                clientIdentity = securityService.login(user, pass);
            } else {
                clientIdentity = securityService.login(realmName, user, pass);
            }
            ClientSecurity.setIdentity(clientIdentity);
        } catch (final LoginException e) {
            throw (AuthenticationException) new AuthenticationException("User could not be authenticated: " + user).initCause(e);
        }
    }
}
 
開發者ID:apache,項目名稱:tomee,代碼行數:23,代碼來源:LocalInitialContext.java


注:本文中的javax.naming.AuthenticationException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。