use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.
the class KapuaSecurityBrokerFilter method removeConnection.
@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
if (!isPassThroughConnection(context)) {
Context loginRemoveConnectionTimeContext = metricLoginRemoveConnectionTime.time();
try {
KapuaSecurityContext kapuaSecurityContext = getKapuaSecurityContext(context);
// TODO fix the kapua session when run as feature will be implemented
KapuaPrincipal kapuaPrincipal = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal());
KapuaSession kapuaSession = new KapuaSession(null, kapuaPrincipal.getAccountId(), kapuaPrincipal.getAccountId(), kapuaPrincipal.getUserId(), kapuaPrincipal.getName());
KapuaSecurityUtils.setSession(kapuaSession);
String clientId = kapuaPrincipal.getClientId();
KapuaId accountId = kapuaPrincipal.getAccountId();
String username = kapuaSecurityContext.getUserName();
String remoteAddress = (context.getConnection() != null) ? context.getConnection().getRemoteAddress() : "";
KapuaId scopeId = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal()).getAccountId();
// multiple account stealing link fix
String fullClientId = MessageFormat.format(AclConstants.MULTI_ACCOUNT_CLIENT_ID, accountId, clientId);
if (!isAdminUser(username)) {
// Stealing link check
ConnectionId connectionId = connectionMap.get(fullClientId);
boolean stealingLinkDetected = false;
if (connectionId != null) {
stealingLinkDetected = !connectionId.equals(info.getConnectionId());
} else {
logger.error("Cannot find connection id for client id {} on connection map. Currect connection id is {} - IP: {}", new Object[] { clientId, info.getConnectionId(), info.getClientIp() });
}
if (stealingLinkDetected) {
metricLoginStealingLinkDisconnect.inc();
// stealing link detected, skip info
logger.warn("Detected Stealing link for cliend id {} - account id {} - last connection id was {} - current connection id is {} - IP: {} - No disconnection info will be added!", new Object[] { clientId, accountId, connectionId, info.getConnectionId(), info.getClientIp() });
} else {
KapuaId deviceConnectionId = kapuaSecurityContext.getConnectionId();
DeviceConnection deviceConnection = null;
try {
deviceConnection = KapuaSecurityUtils.doPriviledge(new Callable<DeviceConnection>() {
@Override
public DeviceConnection call() throws Exception {
return deviceConnectionService.findByClientId(scopeId, clientId);
}
});
} catch (Exception e) {
throw new ShiroException("Error while updating the device connection!", e);
}
// the device connection must be not null
// cleanup stealing link detection map
connectionMap.remove(fullClientId);
final DeviceConnection deviceConnectionToUpdate = deviceConnection;
if (error == null) {
// update device connection
deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.DISCONNECTED);
try {
KapuaSecurityUtils.doPriviledge(() -> {
deviceConnectionService.update(deviceConnectionToUpdate);
return null;
});
} catch (Exception e) {
throw new ShiroException("Error while updating the device connection status!", e);
}
} else {
// send missing message
// update device connection
deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.MISSING);
try {
KapuaSecurityUtils.doPriviledge(() -> {
deviceConnectionService.update(deviceConnectionToUpdate);
return null;
});
} catch (Exception e) {
throw new ShiroException("Error while updating the device connection status!", e);
}
}
}
metricClientDisconnectionClient.inc();
} else {
metricClientDisconnectionKapuasys.inc();
}
// multiple account stealing link fix
info.setClientId(fullClientId);
context.setClientId(fullClientId);
} finally {
loginRemoveConnectionTimeContext.stop();
authenticationService.logout();
}
}
super.removeConnection(context, info, error);
context.setSecurityContext(null);
}
use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.
the class AuthenticationServiceShiroImpl method login.
@Override
public AccessToken login(AuthenticationCredentials authenticationToken) throws KapuaException {
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
logger.info("Thread already authenticated for thread '{}' - '{}' - '{}'", new Object[] { Thread.currentThread().getId(), Thread.currentThread().getName(), currentUser.toString() });
throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.SUBJECT_ALREADY_LOGGED);
}
// AccessToken accessToken = null;
if (authenticationToken instanceof UsernamePasswordTokenImpl) {
UsernamePasswordTokenImpl usernamePasswordToken = (UsernamePasswordTokenImpl) authenticationToken;
MDC.put(KapuaSecurityUtils.MDC_USERNAME, usernamePasswordToken.getUsername());
UsernamePasswordToken shiroToken = new UsernamePasswordToken(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword());
try {
currentUser.login(shiroToken);
Subject shiroSubject = SecurityUtils.getSubject();
Session shiroSession = shiroSubject.getSession();
KapuaEid scopeId = (KapuaEid) shiroSession.getAttribute("scopeId");
KapuaEid userScopeId = (KapuaEid) shiroSession.getAttribute("userScopeId");
KapuaEid userId = (KapuaEid) shiroSession.getAttribute("userId");
// create the access token
String generatedTokenKey = generateToken();
AccessToken accessToken = new AccessTokenImpl(userId, scopeId, userScopeId, generatedTokenKey);
KapuaSession kapuaSession = new KapuaSession(accessToken, scopeId, userScopeId, userId, usernamePasswordToken.getUsername());
KapuaSecurityUtils.setSession(kapuaSession);
shiroSubject.getSession().setAttribute(KapuaSession.KAPUA_SESSION_KEY, kapuaSession);
logger.info("Login for thread '{}' - '{}' - '{}'", new Object[] { Thread.currentThread().getId(), Thread.currentThread().getName(), shiroSubject.toString() });
return kapuaSession.getAccessToken();
} catch (ShiroException se) {
KapuaAuthenticationException kae = null;
if (se instanceof UnknownAccountException) {
kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_USERNAME, se, usernamePasswordToken.getUsername());
} else if (se instanceof DisabledAccountException) {
kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.DISABLED_USERNAME, se, usernamePasswordToken.getUsername());
} else if (se instanceof LockedAccountException) {
kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.LOCKED_USERNAME, se, usernamePasswordToken.getUsername());
} else if (se instanceof IncorrectCredentialsException) {
kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS, se, usernamePasswordToken.getUsername());
} else if (se instanceof ExpiredCredentialsException) {
kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.EXPIRED_CREDENTIALS, se, usernamePasswordToken.getUsername());
} else {
throw KapuaAuthenticationException.internalError(se);
}
currentUser.logout();
throw kae;
}
} else {
throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS_TOKEN_PROVIDED);
}
}
use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.
the class AuthorizationServiceImpl method checkPermission.
@Override
public void checkPermission(Permission permission) throws KapuaException {
KapuaSession session = KapuaSecurityUtils.getSession();
// FIXME: this should throw something like unauthenticated exception
if (session == null) {
throw new KapuaIllegalStateException("null KapuaSession");
}
if (!session.isTrustedMode()) {
Subject subject = SecurityUtils.getSubject();
subject.checkPermission(permission.toString());
}
}
use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.
the class AuthenticationServiceMock method login.
@Override
public AccessToken login(AuthenticationCredentials authenticationToken) throws KapuaException {
if (!(authenticationToken instanceof UsernamePasswordTokenMock))
throw KapuaException.internalError("Unmanaged credentials type");
UsernamePasswordTokenMock usrPwdTokenMock = (UsernamePasswordTokenMock) authenticationToken;
KapuaLocator serviceLocator = KapuaLocator.getInstance();
UserService userService = serviceLocator.getService(UserService.class);
User user = userService.findByName(usrPwdTokenMock.getUsername());
KapuaSession kapuaSession = new KapuaSession(null, null, user.getScopeId(), user.getId(), user.getName());
KapuaSecurityUtils.setSession(kapuaSession);
// TODO Auto-generated method stub
return null;
}
use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.
the class KapuaSessionAuthFilter method executeChain.
protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain) throws IOException, ServletException {
// bind kapua session
// TODO workaround to fix the null kapua session on webconsole requests.
// to be removed and substitute with getToken or another solution?
KapuaSession kapuaSession = null;
Subject shiroSubject = SecurityUtils.getSubject();
if (shiroSubject != null && shiroSubject.isAuthenticated()) {
Session s = shiroSubject.getSession();
KapuaEid scopeId = (KapuaEid) s.getAttribute("scopeId");
KapuaEid userScopeId = (KapuaEid) s.getAttribute("userScopeId");
KapuaEid userId = (KapuaEid) s.getAttribute("userId");
// create the access token
String generatedTokenKey = UUID.randomUUID().toString();
AccessToken accessToken = new AccessTokenImpl(userId, scopeId, userScopeId, generatedTokenKey);
kapuaSession = new KapuaSession(accessToken, scopeId, userScopeId, userId, "");
}
try {
KapuaSecurityUtils.setSession(kapuaSession);
super.executeChain(request, response, origChain);
} finally {
// unbind kapua session
KapuaSecurityUtils.clearSession();
}
}
Aggregations