当前位置: 首页>>代码示例>>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;未经允许,请勿转载。