Search in sources :

Example 56 with Subject

use of org.apache.shiro.subject.Subject in project geode by apache.

the class ServerConnection method doNormalMsg.

private void doNormalMsg() {
    Message msg = null;
    msg = BaseCommand.readRequest(this);
    ThreadState threadState = null;
    try {
        if (msg != null) {
            // launches.
            if (!this.processMessages || (crHelper.isShutdown())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("{} ignoring message of type {} from client {} due to shutdown.", getName(), MessageType.getString(msg.getMessageType()), this.proxyId);
                }
                return;
            }
            if (msg.getMessageType() != MessageType.PING) {
                // check for invalid number of message parts
                if (msg.getNumberOfParts() <= 0) {
                    failureCount++;
                    if (failureCount > 3) {
                        this.processMessages = false;
                        return;
                    } else {
                        return;
                    }
                }
            }
            if (logger.isTraceEnabled()) {
                logger.trace("{} received {} with txid {}", getName(), MessageType.getString(msg.getMessageType()), msg.getTransactionId());
                if (msg.getTransactionId() < -1) {
                    // TODO: why is this happening?
                    msg.setTransactionId(-1);
                }
            }
            if (msg.getMessageType() != MessageType.PING) {
                // we have a real message (non-ping),
                // so let's call receivedPing to let the CHM know client is busy
                acceptor.getClientHealthMonitor().receivedPing(this.proxyId);
            }
            Command command = getCommand(Integer.valueOf(msg.getMessageType()));
            if (command == null) {
                command = Default.getCommand();
            }
            // authorization later
            if (AcceptorImpl.isIntegratedSecurity() && !isInternalMessage() && this.communicationMode != Acceptor.GATEWAY_TO_GATEWAY) {
                long uniqueId = getUniqueId();
                Subject subject = this.clientUserAuths.getSubject(uniqueId);
                if (subject != null) {
                    threadState = securityService.bindSubject(subject);
                }
            }
            command.execute(msg, this);
        }
    } finally {
        // Keep track of the fact that a message is no longer being
        // processed.
        setNotProcessingMessage();
        clearRequestMsg();
        if (threadState != null) {
            threadState.clear();
        }
    }
}
Also used : LocalizedMessage(org.apache.geode.internal.logging.log4j.LocalizedMessage) Command(org.apache.geode.internal.cache.tier.Command) ThreadState(org.apache.shiro.util.ThreadState) Subject(org.apache.shiro.subject.Subject)

Example 57 with Subject

use of org.apache.shiro.subject.Subject in project geode by apache.

the class ServerConnection method setCredentials.

public byte[] setCredentials(Message msg) throws Exception {
    try {
        // need to send back in response with encrption
        if (!AcceptorImpl.isAuthenticationRequired() && msg.isSecureMode()) {
            // This is a CREDENTIALS_NORMAL case.;
            return new byte[0];
        }
        if (!msg.isSecureMode()) {
            throw new AuthenticationFailedException("Authentication failed");
        }
        byte[] secureBytes = msg.getSecureBytes();
        secureBytes = ((HandShake) this.handshake).decryptBytes(secureBytes);
        // need to decrypt it first then get connectionid
        AuthIds aIds = new AuthIds(secureBytes);
        long connId = aIds.getConnectionId();
        if (connId != this.connectionId) {
            throw new AuthenticationFailedException("Authentication failed");
        }
        byte[] credBytes = msg.getPart(0).getSerializedForm();
        credBytes = ((HandShake) this.handshake).decryptBytes(credBytes);
        ByteArrayInputStream bis = new ByteArrayInputStream(credBytes);
        DataInputStream dinp = new DataInputStream(bis);
        Properties credentials = DataSerializer.readProperties(dinp);
        // When here, security is enfored on server, if login returns a subject, then it's the newly
        // integrated security, otherwise, do it the old way.
        long uniqueId;
        DistributedSystem system = this.getDistributedSystem();
        String methodName = system.getProperties().getProperty(SECURITY_CLIENT_AUTHENTICATOR);
        Object principal = HandShake.verifyCredentials(methodName, credentials, system.getSecurityProperties(), (InternalLogWriter) system.getLogWriter(), (InternalLogWriter) system.getSecurityLogWriter(), this.proxyId.getDistributedMember());
        if (principal instanceof Subject) {
            Subject subject = (Subject) principal;
            uniqueId = this.clientUserAuths.putSubject(subject);
            logger.info(this.clientUserAuths);
        } else {
            // this sets principal in map as well....
            uniqueId = ServerHandShakeProcessor.getUniqueId(this, (Principal) principal);
        }
        // create secure part which will be send in respones
        return encryptId(uniqueId, this);
    } catch (AuthenticationFailedException afe) {
        throw afe;
    } catch (AuthenticationRequiredException are) {
        throw are;
    } catch (Exception e) {
        throw new AuthenticationFailedException("REPLY_REFUSED", e);
    }
}
Also used : AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) DataInputStream(java.io.DataInputStream) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributedSystem(org.apache.geode.distributed.DistributedSystem) Subject(org.apache.shiro.subject.Subject) CancelException(org.apache.geode.CancelException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) IOException(java.io.IOException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) ByteArrayInputStream(java.io.ByteArrayInputStream) Principal(java.security.Principal)

Example 58 with Subject

use of org.apache.shiro.subject.Subject in project jena by apache.

the class ShiroExampleEvaluator method evaluate.

/**
	 * This is our internal check to see if the user may access the resource.
	 * This method is called from the evauate(Object,Node) method.
	 * A user may only access the resource if they are authenticated, and are either the
	 * sender or the recipient.
	 * Additionally the admin can always see the messages.
	 * @param principalObj
	 * @param r
	 * @return
	 */
private boolean evaluate(Object principalObj, Resource r) {
    // cast to the Subject because we know that it comes from Shiro and that
    // our getPrincipal() method returns a Subject.
    Subject subject = (Subject) principalObj;
    if (!subject.isAuthenticated()) {
        // we could throw an AuthenticationRequiredException but
        // in our case we just return false.
        LOG.info("User not authenticated");
        return false;
    }
    // a message is only available to sender or recipient
    LOG.debug("checking {}", subject.getPrincipal());
    Object principal = subject.getPrincipal();
    // We put the admin check here but it could have been done much earlier.
    if ("admin".equals(principal.toString())) {
        return true;
    }
    // if we are looking at a message object then check the restrictions.
    if (r.hasProperty(RDF.type, msgType)) {
        return r.hasProperty(pTo, subject.getPrincipal().toString()) || r.hasProperty(pFrom, subject.getPrincipal().toString());
    }
    // otherwise user can see the object.
    return true;
}
Also used : Subject(org.apache.shiro.subject.Subject)

Example 59 with Subject

use of org.apache.shiro.subject.Subject in project bamboobsc by billchen198318.

the class ServiceAuthorityCheckAspect method logicServiceProcess.

@Around(AspectConstants.LOGIC_SERVICE_PACKAGE)
public Object logicServiceProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    String serviceId = AspectConstants.getServiceId(annotations);
    Subject subject = SecurityUtils.getSubject();
    Method method = signature.getMethod();
    if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    if (StringUtils.isBlank(serviceId)) {
        // 沒有 service id 無法判斷檢查 
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    if (!this.isServiceAuthorityCheck(annotations)) {
        // 沒有 ServiceAuthority 或 check=false 就不用檢查了 
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    Annotation[] methodAnnotations = method.getAnnotations();
    if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - " + signature.getMethod().getName());
    SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), false);
    throw new AuthorityException(SysMessageUtil.get(GreenStepSysMsgConstants.NO_PERMISSION));
}
Also used : MethodSignature(org.aspectj.lang.reflect.MethodSignature) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) Subject(org.apache.shiro.subject.Subject) AuthorityException(com.netsteadfast.greenstep.base.exception.AuthorityException) Around(org.aspectj.lang.annotation.Around)

Example 60 with Subject

use of org.apache.shiro.subject.Subject in project bamboobsc by billchen198318.

the class BackgroundProgramUserUtils method login.

public static void login() throws Exception {
    if (factory == null || securityManager == null) {
        throw new Exception("Security manager is null!");
    }
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD);
    subject.login(token);
    subjectThreadLocal.set(subject);
}
Also used : Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Aggregations

Subject (org.apache.shiro.subject.Subject)78 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)11 Test (org.junit.Test)9 IOException (java.io.IOException)8 Map (java.util.Map)8 Path (javax.ws.rs.Path)8 StopProcessingException (ddf.catalog.plugin.StopProcessingException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 AccountVO (com.netsteadfast.greenstep.vo.AccountVO)5 Attribute (ddf.catalog.data.Attribute)5 KeyValueCollectionPermission (ddf.security.permission.KeyValueCollectionPermission)5 GET (javax.ws.rs.GET)5 AuthenticationException (org.apache.shiro.authc.AuthenticationException)5 ServiceException (com.netsteadfast.greenstep.base.exception.ServiceException)4 Metacard (ddf.catalog.data.Metacard)4 ApiOperation (io.swagger.annotations.ApiOperation)4 POST (javax.ws.rs.POST)4 PersistenceException (org.codice.ddf.persistence.PersistenceException)4