下面列出了怎么用javax.naming.AuthenticationException的API类实例代码及写法,或者点击链接到github查看源代码。
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");
}
}
@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
}
}
/**
* 校验用户登录:
*
* @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);
}
/**
* 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;
}
@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());
}
@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();
}
}
@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();
}
}
@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();
}
}
@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();
}
}
@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();
}
}
@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();
}
}
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());
}
}
@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
}
}
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");
}
}
@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;
}
@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;
}
});
}
/**
* 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;
}
public AuthData response(AuthData token) throws AuthenticationException {
try {
return AuthData.of(saslServer.evaluateResponse(token.getBytes()));
} catch (SaslException e) {
log.error("response: Failed to evaluate client token:", e);
throw new AuthenticationException(e.getMessage());
}
}
/**
* Authenticates the API key (if it was specified in the X-Api-Key header)
* and returns a Principal if authentication is successful. Otherwise,
* returns an AuthenticationException.
* @return a Principal of which ApiKey is an instance of
* @throws AuthenticationException upon an authentication failure
* @since 1.0.0
*/
public Principal authenticate() throws AuthenticationException {
try (AlpineQueryManager qm = new AlpineQueryManager()) {
final ApiKey apiKey = qm.getApiKey(assertedApiKey);
if (apiKey == null) {
throw new AuthenticationException();
} else {
return apiKey;
}
}
}
/**
* {@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");
}
if (jwt.getIdentityProvider() == null || IdentityProvider.LOCAL == jwt.getIdentityProvider()) {
final ManagedUser managedUser = qm.getManagedUser(jwt.getSubject());
if (managedUser != null) {
return managedUser.isSuspended() ? null : managedUser;
}
} else if (IdentityProvider.LDAP == jwt.getIdentityProvider()) {
final LdapUser ldapUser = qm.getLdapUser(jwt.getSubject());
if (ldapUser != null) {
return ldapUser;
}
} else if (IdentityProvider.OPENID_CONNECT == jwt.getIdentityProvider()) {
final OidcUser oidcUser = qm.getOidcUser(jwt.getSubject());
if (oidcUser != null) {
return oidcUser;
}
}
}
}
}
return null;
}
@Test
public void authenticateShouldReturnNullWhenBearerIsNull() throws AuthenticationException {
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Basic 123456"));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
assertThat(authService.authenticate()).isNull();
}
@Test
public void authenticateShouldReturnNullWhenTokenIsInvalid() throws AuthenticationException {
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Bearer invalidToken"));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
assertThat(authService.authenticate()).isNull();
}
@Test
public void authenticateShouldThrowExceptionWhenSubjectIsNull() {
final Map<String, Object> tokenClaims = new HashMap<>();
tokenClaims.put("exp", Instant.now().plusSeconds(60).getEpochSecond());
final String token = new JsonWebToken().createToken(tokenClaims);
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Bearer " + token));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(authService::authenticate);
}
@Test
public void authenticateShouldThrowExceptionWhenExpirationIsNull() {
final Map<String, Object> tokenClaims = new HashMap<>();
tokenClaims.put("sub", "subject");
final String token = new JsonWebToken().createToken(tokenClaims);
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Bearer " + token));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(authService::authenticate);
}
/**
* Returns null if authentication has not completed.
* Return auth role if authentication has completed, and httpRequest's role token contains the authRole
*/
public String authRoleFromHttpRequest(HttpServletRequest httpRequest) throws AuthenticationException {
String tokenStr = httpRequest.getHeader(SASL_AUTH_ROLE_TOKEN);
if (tokenStr == null) {
return null;
}
String unSigned = signer.verifyAndExtract(tokenStr);
SaslRoleToken token;
try {
token = SaslRoleToken.parse(unSigned);
if (log.isDebugEnabled()) {
log.debug("server side get role token: {}, session in token:{}, session in request:{}",
token, token.getSession(), httpRequest.getRemoteAddr());
}
} catch (Exception e) {
log.error("token parse failed, with exception: ", e);
return SASL_AUTH_ROLE_TOKEN_EXPIRED;
}
if (!token.isExpired()) {
return token.getUserRole();
} else if (token.isExpired()) {
return SASL_AUTH_ROLE_TOKEN_EXPIRED;
} else {
return null;
}
}
@Test
public void authenticateShouldReturnOidcUserWhenIdentityProviderIsLocal() throws AuthenticationException {
try (final AlpineQueryManager qm = new AlpineQueryManager()) {
qm.createManagedUser("username", "passwordHash");
qm.createLdapUser("username");
final OidcUser oidcUser = new OidcUser();
oidcUser.setUsername("username");
oidcUser.setSubjectIdentifier("subjectIdentifier");
qm.persist(oidcUser);
}
final Principal principalMock = mock(Principal.class);
when(principalMock.getName())
.thenReturn("username");
final String token = new JsonWebToken().createToken(principalMock, null, IdentityProvider.LOCAL);
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Bearer " + token));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
final UserPrincipal authenticatedUser = (UserPrincipal) authService.authenticate();
assertThat(authenticatedUser).isNotNull();
assertThat(authenticatedUser).isInstanceOf(ManagedUser.class);
}
private SearchResult getSingleUser(NamingEnumeration<SearchResult> results) throws NamingException {
if (!results.hasMoreElements()) {
throw new AuthenticationException("User does not exist or not allowed by search string");
}
SearchResult result = results.nextElement();
if (results.hasMoreElements()) {
SearchResult second = results.nextElement();
throw new NamingException(String.format("Ambiguous search, found two users: %s, %s",
result.getNameInNamespace(), second.getNameInNamespace()));
}
return result;
}
/**
* 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);
}
@Override
public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
if (authData instanceof SaslAuthenticationDataSource) {
return ((SaslAuthenticationDataSource)authData).getAuthorizationID();
} else {
throw new AuthenticationException("Not support authDataSource type, expect sasl.");
}
}
/**
* Verifies a signed string and extracts the original string.
*
* @param signedStr the signed string to verify and extract.
*
* @return the extracted original string.
*
* @throws AuthenticationException thrown if the given string is not a signed string or if the signature is invalid.
*/
public String verifyAndExtract(String signedStr) throws AuthenticationException {
int index = signedStr.lastIndexOf(SIGNATURE);
if (index == -1) {
throw new AuthenticationException("Invalid signed text: " + signedStr);
}
String originalSignature = signedStr.substring(index + SIGNATURE.length());
String rawValue = signedStr.substring(0, index);
String currentSignature = computeSignature(rawValue);
if (!originalSignature.equals(currentSignature)) {
throw new AuthenticationException("Invalid signature");
}
return rawValue;
}