use of javax.security.auth.Subject in project jstorm by alibaba.
the class KerberosSaslTransportPlugin method connect.
@Override
public TTransport connect(TTransport transport, String serverHost, String asUser) throws TTransportException, IOException {
// create an authentication callback handler
ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);
// login our user
Login login = null;
try {
// specify a configuration object to be used
Configuration.setConfiguration(login_conf);
// now login
login = new Login(AuthUtils.LOGIN_CONTEXT_CLIENT, client_callback_handler);
} catch (LoginException ex) {
LOG.error("Server failed to login in principal:" + ex, ex);
throw new RuntimeException(ex);
}
final Subject subject = login.getSubject();
if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) {
// error
throw new RuntimeException("Fail to verify user principal with section \"" + AuthUtils.LOGIN_CONTEXT_CLIENT + "\" in login configuration file " + login_conf);
}
final String principal = StringUtils.isBlank(asUser) ? getPrincipal(subject) : asUser;
String serviceName = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_CLIENT, "serviceName");
if (serviceName == null) {
serviceName = AuthUtils.SERVICE;
}
Map<String, String> props = new TreeMap<String, String>();
props.put(Sasl.QOP, "auth");
props.put(Sasl.SERVER_AUTH, "false");
LOG.debug("SASL GSSAPI client transport is being established");
final TTransport sasalTransport = new TSaslClientTransport(KERBEROS, principal, serviceName, serverHost, props, null, transport);
// open Sasl transport with the login credential
try {
Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
public Void run() {
try {
LOG.debug("do as:" + principal);
sasalTransport.open();
} catch (Exception e) {
LOG.error("Client failed to open SaslClientTransport to interact with a server during session initiation: " + e, e);
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e);
}
return sasalTransport;
}
use of javax.security.auth.Subject in project jstorm by alibaba.
the class SingleUserSimpleTransport method getDefaultSubject.
@Override
protected Subject getDefaultSubject() {
HashSet<Principal> principals = new HashSet<Principal>();
principals.add(new Principal() {
public String getName() {
return "user";
}
public String toString() {
return "user";
}
});
return new Subject(true, principals, new HashSet<Object>(), new HashSet<Object>());
}
use of javax.security.auth.Subject in project cassandra by apache.
the class AuthenticationProxy method authenticate.
/**
* Perform authentication of the client opening the {@code}MBeanServerConnection{@code}
*
* @param credentials optionally these credentials may be supplied by the JMX user.
* Out of the box, the JDK's {@code}RMIServerImpl{@code} is capable
* of supplying a two element String[], containing username and password.
* If present, these credentials will be made available to configured
* {@code}LoginModule{@code}s via {@code}JMXCallbackHandler{@code}.
*
* @return the authenticated subject containing any {@code}Principal{@code}s added by
*the {@code}LoginModule{@code}s
*
* @throws SecurityException if the server cannot authenticate the user
* with the provided credentials.
*/
public Subject authenticate(Object credentials) {
// The credentials object is expected to be a string array holding the subject's
// username & password. Those values are made accessible to LoginModules via the
// JMXCallbackHandler.
JMXCallbackHandler callbackHandler = new JMXCallbackHandler(credentials);
try {
LoginContext loginContext = new LoginContext(loginConfigName, callbackHandler);
loginContext.login();
final Subject subject = loginContext.getSubject();
if (!subject.isReadOnly()) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
subject.setReadOnly();
return null;
});
}
return subject;
} catch (LoginException e) {
logger.trace("Authentication exception", e);
throw new SecurityException("Authentication error", e);
}
}
use of javax.security.auth.Subject in project camel by apache.
the class SpringSecurityAuthorizationPolicyTest method sendMessageWithAuthentication.
private void sendMessageWithAuthentication(String username, String password, String... roles) {
Authentication authToken = createAuthenticationToken(username, password, roles);
Subject subject = new Subject();
subject.getPrincipals().add(authToken);
template.sendBodyAndHeader("direct:start", "hello world", Exchange.AUTHENTICATION, subject);
}
use of javax.security.auth.Subject in project camel by apache.
the class HttpServerChannelHandler method messageReceived.
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
HttpRequest request = (HttpRequest) messageEvent.getMessage();
LOG.debug("Message received: {}", request);
if (consumer.isSuspended()) {
// are we suspended?
LOG.debug("Consumer suspended, cannot service request {}", request);
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
response.setChunked(false);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
}
// if its an OPTIONS request then return which methods is allowed
boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
if ("OPTIONS".equals(request.getMethod().getName()) && !isRestrictedToOptions) {
String s;
if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
} else {
// allow them all
s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
}
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
response.setChunked(false);
response.headers().set("Allow", s);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
}
if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().getName())) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
response.setChunked(false);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
}
if ("TRACE".equals(request.getMethod().getName()) && !consumer.getEndpoint().isTraceEnabled()) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
response.setChunked(false);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
}
// must include HOST header as required by HTTP 1.1
if (!request.headers().contains(HttpHeaders.Names.HOST)) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
response.setChunked(false);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
}
// is basic auth configured
NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
String url = request.getUri();
// drop parameters from url
if (url.contains("?")) {
url = ObjectHelper.before(url, "?");
}
// we need the relative path without the hostname and port
URI uri = new URI(request.getUri());
String target = uri.getPath();
// strip the starting endpoint path so the target is relative to the endpoint uri
String path = consumer.getConfiguration().getPath();
if (path != null) {
// need to match by lower case as we want to ignore case on context-path
path = path.toLowerCase(Locale.US);
String match = target.toLowerCase(Locale.US);
if (match.startsWith(path)) {
target = target.substring(path.length());
}
}
// is it a restricted resource?
String roles;
if (security.getSecurityConstraint() != null) {
// if restricted returns null, then the resource is not restricted and we should not authenticate the user
roles = security.getSecurityConstraint().restricted(target);
} else {
// assume any roles is valid if no security constraint has been configured
roles = "*";
}
if (roles != null) {
// basic auth subject
HttpPrincipal principal = extractBasicAuthSubject(request);
// authenticate principal and check if the user is in role
Subject subject = null;
boolean inRole = true;
if (principal != null) {
subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
if (subject != null) {
String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
inRole = matchesRoles(roles, userRoles);
}
}
if (principal == null || subject == null || !inRole) {
if (principal == null) {
LOG.debug("Http Basic Auth required for resource: {}", url);
} else if (subject == null) {
LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
} else {
LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
}
// restricted resource, so send back 401 to require valid username/password
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
messageEvent.getChannel().write(response).syncUninterruptibly();
messageEvent.getChannel().close();
return;
} else {
LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
}
}
}
// let Camel process this message
// It did the way as camel-netty component does
super.messageReceived(ctx, messageEvent);
}
Aggregations