javax.naming.AuthenticationException Java Examples
The following examples show how to use
javax.naming.AuthenticationException.
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: MenuConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public MenuConfig addMenuConfig(long userId, long groupId, String menuGroup, String menuName, Integer order, Integer menuType, String queryParams, String tableConfig, String buttonConfig, String icon, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { MenuConfig object = null; object = MenuConfigLocalServiceUtil.addMenuConfig(userId, groupId, menuGroup, menuName, order, menuType, queryParams, tableConfig, buttonConfig, icon); return object; } else { throw new AuthenticationException(); } }
Example #2
Source File: SearchFirstActiveDirectoryRealm.java From centraldogma with Apache License 2.0 | 6 votes |
@Nullable private AuthenticationInfo queryForAuthenticationInfo0( AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException { final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token); final String userDn = findUserDn(ldapContextFactory, upToken.getUsername()); if (userDn == null) { return null; } LdapContext ctx = null; try { // Binds using the username and password provided by the user. ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword()); } catch (AuthenticationException e) { // According to this page, LDAP error code 49 (invalid credentials) is the only case where // AuthenticationException is raised: // - https://docs.oracle.com/javase/tutorial/jndi/ldap/exceptions.html // - com.sun.jndi.ldap.LdapCtx.mapErrorCode() return null; } finally { LdapUtils.closeContext(ctx); } return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword()); }
Example #3
Source File: SaslRoleToken.java From pulsar with Apache License 2.0 | 6 votes |
/** * Splits the string representation of a token into attributes pairs. * * @param tokenStr string representation of a token. * * @return a map with the attribute pairs of the token. * * @throws AuthenticationException thrown if the string representation of the token could not be broken into * attribute pairs. */ private static Map<String, String> split(String tokenStr) throws AuthenticationException { Map<String, String> map = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(tokenStr, ATTR_SEPARATOR); while (st.hasMoreTokens()) { String part = st.nextToken(); int separator = part.indexOf('='); if (separator == -1) { throw new AuthenticationException("Invalid authentication token"); } String key = part.substring(0, separator); String value = part.substring(separator + 1); map.put(key, value); } return map; }
Example #4
Source File: AuthenticationProviderToken.java From pulsar with Apache License 2.0 | 6 votes |
@Override public AuthData authenticate(AuthData authData) throws AuthenticationException { String token = new String(authData.getBytes(), UTF_8); this.jwt = provider.authenticateToken(token); this.authenticationDataSource = new AuthenticationDataCommand(token, remoteAddress, sslSession); if (jwt.getBody().getExpiration() != null) { this.expiration = jwt.getBody().getExpiration().getTime(); } else { // Disable expiration this.expiration = Long.MAX_VALUE; } // There's no additional auth stage required return null; }
Example #5
Source File: AuthenticationProviderTokenTest.java From pulsar with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = AuthenticationException.class) public void testAuthenticateWhenInvalidTokenIsPassed() throws AuthenticationException, IOException { SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256); Properties properties = new Properties(); properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_SECRET_KEY, AuthTokenUtils.encodeKeyBase64(secretKey)); ServiceConfiguration conf = new ServiceConfiguration(); conf.setProperties(properties); AuthenticationProviderToken provider = new AuthenticationProviderToken(); provider.initialize(conf); provider.authenticate(new AuthenticationDataSource() { @Override public String getHttpHeader(String name) { return AuthenticationProviderToken.HTTP_HEADER_VALUE_PREFIX + "invalid_token"; } @Override public boolean hasDataFromHttp() { return true; } }); }
Example #6
Source File: PulsarSaslClient.java From pulsar with Apache License 2.0 | 6 votes |
public AuthData evaluateChallenge(final AuthData saslToken) throws AuthenticationException { if (saslToken == null) { throw new AuthenticationException("saslToken is null"); } try { if (clientSubject != null) { final byte[] retval = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() { @Override public byte[] run() throws SaslException { return saslClient.evaluateChallenge(saslToken.getBytes()); } }); return AuthData.of(retval); } else { return AuthData.of(saslClient.evaluateChallenge(saslToken.getBytes())); } } catch (Exception e) { log.error("SASL error", e.getCause()); throw new AuthenticationException("SASL/JAAS error" + e.getCause()); } }
Example #7
Source File: AuthenticationProviderAthenzTest.java From pulsar with Apache License 2.0 | 6 votes |
@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", 0), null); try { provider.authenticate(authData); fail("Token which has different domain should not be authenticated"); } catch (AuthenticationException e) { // OK, expected } }
Example #8
Source File: StepConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public StepConfig updateStepConfig(Long stepConfigId, long userId, long groupId, String stepCode, String stepName, Integer stepType, String dossierStatus, String dossierSubStatus, String menuGroup, String menuStepName, String buttonConfig, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { StepConfig object; object = StepConfigLocalServiceUtil.updateStepConfig(stepConfigId, userId, groupId, stepCode, stepName, stepType, dossierStatus, dossierSubStatus, menuGroup, menuStepName, buttonConfig); return object; } else { throw new AuthenticationException(); } }
Example #9
Source File: StepConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public StepConfig addStepConfig(long userId, long groupId, String stepCode, String stepName, Integer stepType, String dossierStatus, String dossierSubStatus, String menuGroup, String menuStepName, String buttonConfig, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { StepConfig object = null; if (Validator.isNotNull(stepCode)) { object = StepConfigLocalServiceUtil.addStepConfig(userId, groupId, stepCode, stepName, stepType, dossierStatus, dossierSubStatus, menuGroup, menuStepName, buttonConfig); } return object; } else { throw new AuthenticationException(); } }
Example #10
Source File: ActionConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public ActionConfig updateActionConfig(Long actionConfigId, long userId, long groupId, String actionCode, String actionName, Boolean extraForm, String formScript, String sampleData, Boolean insideProcess, Integer userNote, Integer syncType, Boolean pending, Boolean rollbackable, String notificationType, String documentType, String mappingAction, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { ActionConfig object = ActionConfigLocalServiceUtil.getActionConfig(actionConfigId); object = ActionConfigLocalServiceUtil.updateActionConfig(object.getActionConfigId(), userId, groupId, actionCode, actionName, extraForm, formScript, sampleData, insideProcess, userNote, syncType, pending, rollbackable, notificationType, documentType, mappingAction); return object; } else { throw new AuthenticationException(); } }
Example #11
Source File: ActionConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public ActionConfig addActionConfig(long userId, long groupId, String actionCode, String actionName, Boolean extraForm, String formScript, String sampleData, Boolean insideProcess, Integer userNote, Integer syncType, Boolean pending, Boolean rollbackable, String notificationType, String documentType, String mappingAction, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { ActionConfig object = null; if (Validator.isNotNull(actionCode)) { object = ActionConfigLocalServiceUtil.addActionConfig(userId, groupId, actionCode, actionName, extraForm, formScript, sampleData, insideProcess, userNote, syncType, pending, rollbackable, notificationType, documentType, mappingAction); } return object; } else { throw new AuthenticationException(); } }
Example #12
Source File: WebSocketWebResource.java From pulsar with Apache License 2.0 | 6 votes |
/** * 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; }
Example #13
Source File: CheckLoginServiceListener.java From MicroCommunity with Apache License 2.0 | 6 votes |
/** * 校验用户登录: * * @param event */ @Override public void soService(ServiceDataFlowEvent event) { //获取数据上下文对象 DataFlowContext dataFlowContext = event.getDataFlowContext(); AppService service = event.getAppService(); String paramIn = dataFlowContext.getReqData(); Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn); Assert.jsonObjectHaveKey(paramIn,"token","请求报文中未包含token 节点请检查"); JSONObject paramObj = JSONObject.parseObject(paramIn); ResponseEntity responseEntity= null; try { Map<String, String> claims = AuthenticationFactory.verifyToken(paramObj.getString("token")); if(claims == null || claims.isEmpty()){ throw new AuthenticationException("认证失败,从token中解析到信息为空"); } JSONObject resultInfo = new JSONObject(); resultInfo.put("userId",claims.get("userId")); responseEntity = new ResponseEntity<String>(resultInfo.toJSONString(), HttpStatus.OK); } catch (Exception e) { //Invalid signature/claims responseEntity = new ResponseEntity<String>("认证失败,不是有效的token", HttpStatus.UNAUTHORIZED); } dataFlowContext.setResponseEntity(responseEntity); }
Example #14
Source File: AuthenticationProviderAthenzTest.java From pulsar with Apache License 2.0 | 6 votes |
@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", 0), null); try { provider.authenticate(authData); fail("Unsigned token should not be authenticated"); } catch (AuthenticationException e) { // OK, expected } }
Example #15
Source File: MenuConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 6 votes |
@Override public MenuConfig updateMenuConfig(long actionCodePK, long userId, long groupId, String menuGroup, String menuName, Integer order, Integer menuType, String queryParams, String tableConfig, String buttonConfig, String icon, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { MenuConfig object = null; object = MenuConfigLocalServiceUtil.updateMenuConfig(actionCodePK, userId, groupId, menuGroup, menuName, order, menuType, queryParams, tableConfig, buttonConfig, icon); return object; } else { throw new AuthenticationException(); } }
Example #16
Source File: LdapAuthenticator.java From presto with Apache License 2.0 | 6 votes |
private DirContext createUserDirContext(String userDistinguishedName, String password) throws NamingException { Map<String, String> environment = createEnvironment(userDistinguishedName, password); try { // This is the actual Authentication piece. Will throw javax.naming.AuthenticationException // if the users password is not correct. Other exceptions may include IO (server not found) etc. DirContext context = createDirContext(environment); log.debug("Password validation successful for user DN [%s]", userDistinguishedName); return context; } catch (AuthenticationException e) { log.debug("Password validation failed for user DN [%s]: %s", userDistinguishedName, e.getMessage()); throw new AccessDeniedException("Invalid credentials"); } }
Example #17
Source File: AuthenticationProviderToken.java From pulsar with Apache License 2.0 | 6 votes |
public static String getToken(AuthenticationDataSource authData) throws AuthenticationException { if (authData.hasDataFromCommand()) { // Authenticate Pulsar binary connection return validateToken(authData.getCommandData()); } else if (authData.hasDataFromHttp()) { // Authentication HTTP request. The format here should be compliant to RFC-6750 // (https://tools.ietf.org/html/rfc6750#section-2.1). Eg: Authorization: Bearer xxxxxxxxxxxxx String httpHeaderValue = authData.getHttpHeader(HTTP_HEADER_NAME); if (httpHeaderValue == null || !httpHeaderValue.startsWith(HTTP_HEADER_VALUE_PREFIX)) { throw new AuthenticationException("Invalid HTTP Authorization header"); } // Remove prefix String token = httpHeaderValue.substring(HTTP_HEADER_VALUE_PREFIX.length()); return validateToken(token); } else { throw new AuthenticationException("No token credentials passed"); } }
Example #18
Source File: ExceptionFinder.java From dr-elephant with Apache License 2.0 | 5 votes |
/** * Constructor for ExceptionFinder class * @param url The url of the workflow to analyze * @param scheduler The scheduler where the workflow was run. * @throws URISyntaxException * @throws MalformedURLException */ public ExceptionFinder(String url, String scheduler) throws URISyntaxException, MalformedURLException, AuthenticationException, IOException { // create a new MRClient _mrClient = new MRClient(); // create a new workflow client _workflowClient = InfoExtractor.getWorkflowClientInstance(scheduler, url); // get the schedulerData SchedulerConfigurationData schedulerData = InfoExtractor.getSchedulerData(scheduler); if(schedulerData==null) { throw new RuntimeException(String.format("Cannot find scheduler %s", scheduler)); } if (schedulerData.getParamMap().containsKey("exception_enabled") == false || schedulerData.getParamMap().get("exception_enabled").equals("false")) { throw new RuntimeException(String.format("Scheduler %s is not configured for Exception fingerprinting ", scheduler)); } if(!schedulerData.getParamMap().containsKey(USERNAME)) { throw new RuntimeException(String.format("Cannot find username for login")); } String username = schedulerData.getParamMap().get(USERNAME); if(schedulerData.getParamMap().containsKey(PRIVATE_KEY)) { _workflowClient.login(username, new File(schedulerData.getParamMap().get(PRIVATE_KEY))); } else if (schedulerData.getParamMap().containsKey(PASSWORD)) { _workflowClient.login(username, schedulerData.getParamMap().get(PASSWORD)); } else { throw new RuntimeException("Neither private key nor password was specified"); } _exception = analyzeFlow(url); }
Example #19
Source File: JNDIRealm.java From tomcatsrc with Apache License 2.0 | 5 votes |
/** * Check credentials by binding to the directory as the user * * @param context The directory context * @param user The User to be authenticated * @param credentials Authentication credentials * * @exception NamingException if a directory server error occurs */ protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException { if (credentials == null || user == null) return (false); String dn = user.getDN(); if (dn == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) { containerLog.trace(" validating credentials by binding as the user"); } userCredentialsAdd(context, dn, credentials); // Elicit an LDAP bind operation boolean validated = false; try { if (containerLog.isTraceEnabled()) { containerLog.trace(" binding as " + dn); } context.getAttributes("", null); validated = true; } catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } } userCredentialsRemove(context); return validated; }
Example #20
Source File: ProxyRolesEnforcementTest.java From pulsar with Apache License 2.0 | 5 votes |
@Override public String authenticate(AuthenticationDataSource authData) throws AuthenticationException { if (authData.hasDataFromCommand()) { return authData.getCommandData(); } else if (authData.hasDataFromHttp()) { return authData.getHttpHeader("BasicAuthentication"); } return null; }
Example #21
Source File: AuthenticationProviderToken.java From pulsar with Apache License 2.0 | 5 votes |
private static String validateToken(final String token) throws AuthenticationException { if (StringUtils.isNotBlank(token)) { return token; } else { throw new AuthenticationException("Blank token found"); } }
Example #22
Source File: AuthenticationProviderBasic.java From pulsar with Apache License 2.0 | 5 votes |
@Override public String authenticate(AuthenticationDataSource authData) throws AuthenticationException { AuthParams authParams = new AuthParams(authData); String userId = authParams.getUserId(); String password = authParams.getPassword(); String msg = "Unknown user or invalid password"; if (users.get(userId) == null) { throw new AuthenticationException(msg); } String encryptedPassword = users.get(userId); // For md5 algorithm if ((users.get(userId).startsWith("$apr1"))) { List<String> splitEncryptedPassword = Arrays.asList(encryptedPassword.split("\\$")); if (splitEncryptedPassword.size() != 4 || !encryptedPassword .equals(Md5Crypt.apr1Crypt(password.getBytes(), splitEncryptedPassword.get(2)))) { throw new AuthenticationException(msg); } // For crypt algorithm } else if (!encryptedPassword.equals(Crypt.crypt(password.getBytes(), encryptedPassword.substring(0, 2)))) { throw new AuthenticationException(msg); } return userId; }
Example #23
Source File: AuthenticationProviderBasic.java From pulsar with Apache License 2.0 | 5 votes |
public AuthParams(AuthenticationDataSource authData) throws AuthenticationException { String authParams; if (authData.hasDataFromCommand()) { authParams = authData.getCommandData(); } else if (authData.hasDataFromHttp()) { String rawAuthToken = authData.getHttpHeader(HTTP_HEADER_NAME); // parsing and validation if (StringUtils.isBlank(rawAuthToken) || !rawAuthToken.toUpperCase().startsWith("BASIC ")) { throw new AuthenticationException("Authentication token has to be started with \"Basic \""); } String[] splitRawAuthToken = rawAuthToken.split(" "); if (splitRawAuthToken.length != 2) { throw new AuthenticationException("Base64 encoded token is not found"); } try { authParams = new String(Base64.getDecoder().decode(splitRawAuthToken[1])); } catch (Exception e) { throw new AuthenticationException("Base64 decoding is failure: " + e.getMessage()); } } else { throw new AuthenticationException("Authentication data source does not have data"); } String[] parsedAuthParams = authParams.split(":"); if (parsedAuthParams.length != 2) { throw new AuthenticationException("Base64 decoded params are invalid"); } userId = parsedAuthParams[0]; password = parsedAuthParams[1]; }
Example #24
Source File: OneStageAuthenticationState.java From pulsar with Apache License 2.0 | 5 votes |
public OneStageAuthenticationState(AuthData authData, SocketAddress remoteAddress, SSLSession sslSession, AuthenticationProvider provider) throws AuthenticationException { this.authenticationDataSource = new AuthenticationDataCommand( new String(authData.getBytes(), UTF_8), remoteAddress, sslSession); this.authRole = provider.authenticate(authenticationDataSource); }
Example #25
Source File: AuthenticationProviderToken.java From pulsar with Apache License 2.0 | 5 votes |
@Override public String authenticate(AuthenticationDataSource authData) throws AuthenticationException { // Get Token String token = getToken(authData); // Parse Token by validating return getPrincipal(authenticateToken(token)); }
Example #26
Source File: AuthenticationProviderToken.java From pulsar with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private Jwt<?, Claims> authenticateToken(final String token) throws AuthenticationException { try { Jwt<?, Claims> jwt = Jwts.parser() .setSigningKey(validationKey) .parse(token); if (audienceClaim != null) { Object object = jwt.getBody().get(audienceClaim); if (object == null) { throw new JwtException("Found null Audience in token, for claimed field: " + audienceClaim); } if (object instanceof List) { List<String> audiences = (List<String>) object; // audience not contains this broker, throw exception. if (!audiences.stream().anyMatch(audienceInToken -> audienceInToken.equals(audience))) { throw new AuthenticationException("Audiences in token: [" + String.join(", ", audiences) + "] not contains this broker: " + audience); } } else if (object instanceof String) { if (!object.equals(audience)) { throw new AuthenticationException("Audiences in token: [" + object + "] not contains this broker: " + audience); } } else { // should not reach here. throw new AuthenticationException("Audiences in token is not in expected format: " + object); } } return jwt; } catch (JwtException e) { throw new AuthenticationException("Failed to authentication token: " + e.getMessage()); } }
Example #27
Source File: ServerConnection.java From pulsar with Apache License 2.0 | 5 votes |
/** * handles connect request and sends {@code State.Connected} ack to client */ @Override protected void handleConnect(CommandConnect connect) { checkArgument(state == State.Start); if (LOG.isDebugEnabled()) { LOG.debug("Received CONNECT from {}", remoteAddress); } if(service.getConfiguration().isAuthenticationEnabled()) { try { String authMethod = "none"; if (connect.hasAuthMethodName()) { authMethod = connect.getAuthMethodName(); } else if (connect.hasAuthMethod()) { // Legacy client is passing enum authMethod = connect.getAuthMethod().name().substring(10).toLowerCase(); } String authData = connect.getAuthData().toStringUtf8(); ChannelHandler sslHandler = ctx.channel().pipeline().get(TLS_HANDLER); SSLSession sslSession = null; if (sslHandler != null) { sslSession = ((SslHandler) sslHandler).engine().getSession(); } this.authenticationData = new AuthenticationDataCommand(authData, remoteAddress, sslSession); authRole = service.getAuthenticationService() .authenticate(this.authenticationData, authMethod); LOG.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod, authRole); } catch (AuthenticationException e) { String msg = "Unable to authenticate"; LOG.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage()); ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg)); close(); return; } } ctx.writeAndFlush(Commands.newConnected(connect.getProtocolVersion())); state = State.Connected; remoteEndpointProtocolVersion = connect.getProtocolVersion(); }
Example #28
Source File: StepConfigActionsImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override public void deleteStepConfig(Long stepConfigId, ServiceContext serviceContext) throws PortalException, AuthenticationException { BackendAuthImpl authImpl = new BackendAuthImpl(); if (authImpl.hasResource(serviceContext, StringPool.BLANK, StringPool.BLANK)) { StepConfigLocalServiceUtil.removeStepConfig(stepConfigId); } else { throw new AuthenticationException(); } }
Example #29
Source File: AuthenticationProviderSasl.java From pulsar with Apache License 2.0 | 5 votes |
@Override public AuthenticationState newAuthState(AuthData authData, SocketAddress remoteAddress, SSLSession sslSession) throws AuthenticationException { try { return new SaslAuthenticationState( new SaslAuthenticationDataSource( new PulsarSaslServer(jaasCredentialsContainer.getSubject(), allowedIdsPattern))); } catch (Throwable t) { log.error("Failed create sasl auth state" , t); throw new AuthenticationException(t.getMessage()); } }
Example #30
Source File: SaslRoleToken.java From pulsar with Apache License 2.0 | 5 votes |
/** * Parses a string into an authentication token. * * @param tokenStr string representation of a token. * * @return the parsed authentication token. * * @throws AuthenticationException thrown if the string representation could not be parsed into * an authentication token. */ public static SaslRoleToken parse(String tokenStr) throws AuthenticationException { Map<String, String> map = split(tokenStr); if (!map.keySet().equals(ATTRIBUTES)) { throw new AuthenticationException("Invalid token string, missing attributes"); } long expires = Long.parseLong(map.get(EXPIRES)); SaslRoleToken token = new SaslRoleToken(map.get(USER_ROLE), map.get(SESSION)); token.setExpires(expires); return token; }