Search in sources :

Example 46 with Subject

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

the class LoginRestApi method postLogin.

/**
   * Post Login
   * Returns userName & password
   * for anonymous access, username is always anonymous.
   * After getting this ticket, access through websockets become safe
   *
   * @return 200 response
   */
@POST
@ZeppelinApi
public Response postLogin(@FormParam("userName") String userName, @FormParam("password") String password) {
    JsonResponse response = null;
    // ticket set to anonymous for anonymous user. Simplify testing.
    Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
    if (currentUser.isAuthenticated()) {
        currentUser.logout();
    }
    if (!currentUser.isAuthenticated()) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            //      token.setRememberMe(true);
            currentUser.login(token);
            HashSet<String> roles = SecurityUtils.getRoles();
            String principal = SecurityUtils.getPrincipal();
            String ticket;
            if ("anonymous".equals(principal))
                ticket = "anonymous";
            else
                ticket = TicketContainer.instance.getTicket(principal);
            Map<String, String> data = new HashMap<>();
            data.put("principal", principal);
            data.put("roles", roles.toString());
            data.put("ticket", ticket);
            response = new JsonResponse(Response.Status.OK, "", data);
            //if no exception, that's it, we're done!
            //set roles for user in NotebookAuthorization module
            NotebookAuthorization.getInstance().setRoles(principal, roles);
        } catch (UnknownAccountException uae) {
            //username wasn't in the system, show them an error message?
            LOG.error("Exception in login: ", uae);
        } catch (IncorrectCredentialsException ice) {
            //password didn't match, try again?
            LOG.error("Exception in login: ", ice);
        } catch (LockedAccountException lae) {
            //account for that username is locked - can't login.  Show them a message?
            LOG.error("Exception in login: ", lae);
        } catch (AuthenticationException ae) {
            //unexpected condition - error?
            LOG.error("Exception in login: ", ae);
        }
    }
    if (response == null) {
        response = new JsonResponse(Response.Status.FORBIDDEN, "", "");
    }
    LOG.warn(response.toString());
    return response.build();
}
Also used : HashMap(java.util.HashMap) JsonResponse(org.apache.zeppelin.server.JsonResponse) Subject(org.apache.shiro.subject.Subject) ZeppelinApi(org.apache.zeppelin.annotation.ZeppelinApi) POST(javax.ws.rs.POST)

Example 47 with Subject

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

the class SecurityUtils method getPrincipal.

/**
   * Return the authenticated user if any otherwise returns "anonymous"
   *
   * @return shiro principal
   */
public static String getPrincipal() {
    if (!isEnabled) {
        return ANONYMOUS;
    }
    Subject subject = org.apache.shiro.SecurityUtils.getSubject();
    String principal;
    if (subject.isAuthenticated()) {
        principal = subject.getPrincipal().toString();
    } else {
        principal = ANONYMOUS;
    }
    return principal;
}
Also used : Subject(org.apache.shiro.subject.Subject)

Example 48 with Subject

use of org.apache.shiro.subject.Subject in project cas by apereo.

the class ShiroAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    try {
        final UsernamePasswordToken token = new UsernamePasswordToken(transformedCredential.getUsername(), transformedCredential.getPassword());
        if (transformedCredential instanceof RememberMeUsernamePasswordCredential) {
            token.setRememberMe(RememberMeUsernamePasswordCredential.class.cast(transformedCredential).isRememberMe());
        }
        final Subject currentUser = getCurrentExecutingSubject();
        currentUser.login(token);
        checkSubjectRolesAndPermissions(currentUser);
        return createAuthenticatedSubjectResult(transformedCredential, currentUser);
    } catch (final UnknownAccountException uae) {
        throw new AccountNotFoundException(uae.getMessage());
    } catch (final IncorrectCredentialsException ice) {
        throw new FailedLoginException(ice.getMessage());
    } catch (final LockedAccountException | ExcessiveAttemptsException lae) {
        throw new AccountLockedException(lae.getMessage());
    } catch (final ExpiredCredentialsException eae) {
        throw new CredentialExpiredException(eae.getMessage());
    } catch (final DisabledAccountException eae) {
        throw new AccountDisabledException(eae.getMessage());
    } catch (final AuthenticationException e) {
        throw new FailedLoginException(e.getMessage());
    }
}
Also used : DisabledAccountException(org.apache.shiro.authc.DisabledAccountException) IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AccountLockedException(javax.security.auth.login.AccountLockedException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) Subject(org.apache.shiro.subject.Subject) ExpiredCredentialsException(org.apache.shiro.authc.ExpiredCredentialsException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) CredentialExpiredException(javax.security.auth.login.CredentialExpiredException) RememberMeUsernamePasswordCredential(org.apereo.cas.authentication.RememberMeUsernamePasswordCredential) LockedAccountException(org.apache.shiro.authc.LockedAccountException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException)

Example 49 with Subject

use of org.apache.shiro.subject.Subject in project qi4j-sdk by Qi4j.

the class SecurityConcern method invoke.

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Subject subject = SecurityUtils.getSubject();
    handleRequiresGuest(subject);
    handleRequiresUser(subject);
    handleRequiresAuthentication(subject);
    handleRequiresRoles(subject);
    handleRequiresPermissions(subject);
    return next.invoke(proxy, method, args);
}
Also used : Subject(org.apache.shiro.subject.Subject)

Example 50 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class SessionAuthenticator method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    SessionIdToken sessionIdToken = (SessionIdToken) token;
    final Subject subject = new Subject.Builder().sessionId(sessionIdToken.getSessionId()).buildSubject();
    final Session session = subject.getSession(false);
    if (session == null) {
        LOG.debug("Invalid session {}. Either it has expired or did not exist.", sessionIdToken.getSessionId());
        return null;
    }
    final Object username = subject.getPrincipal();
    final User user = userService.load(String.valueOf(username));
    if (user == null) {
        LOG.debug("No user named {} found for session {}", username, sessionIdToken.getSessionId());
        return null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Found session {} for user name {}", session.getId(), username);
    }
    @SuppressWarnings("unchecked") final MultivaluedMap<String, String> requestHeaders = (MultivaluedMap<String, String>) ThreadContext.get(ShiroSecurityContextFilter.REQUEST_HEADERS);
    // extend session unless the relevant header was passed.
    if (requestHeaders != null && !"true".equalsIgnoreCase(requestHeaders.getFirst(X_GRAYLOG_NO_SESSION_EXTENSION))) {
        session.touch();
    } else {
        LOG.debug("Not extending session because the request indicated not to.");
    }
    ThreadContext.bind(subject);
    return new SimpleAccount(user.getName(), null, "session authenticator");
}
Also used : SimpleAccount(org.apache.shiro.authc.SimpleAccount) User(org.graylog2.plugin.database.users.User) SessionIdToken(org.graylog2.shared.security.SessionIdToken) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session)

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