Search in sources :

Example 6 with Subject

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

the class StandaloneShiroTest method test.

@Test
public void test() {
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();
    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    assertEquals("aValue", value);
    LOG.info("Retrieved the correct value! [" + value + "]");
    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            fail("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            fail("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            fail("The account for username " + token.getPrincipal() + " is locked.  " + "Please contact your administrator to unlock it.");
        }// ... catch more exceptions here (maybe custom ones specific to your application?
         catch (AuthenticationException ae) {
            //unexpected condition?  error?
            throw ae;
        }
    }
    //say who they are:
    //print their identifying principal (in this case, a username):
    assertNotNull(currentUser.getPrincipal());
    LOG.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    //test a role:
    if (currentUser.hasRole("schwartz")) {
        LOG.info("May the Schwartz be with you!");
    } else {
        fail("Hello, mere mortal.");
    }
    //test a typed permission (not instance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        LOG.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        fail("Sorry, lightsaber rings are for schwartz masters only.");
    }
    //a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        LOG.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " + "Here are the keys - have fun!");
    } else {
        fail("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }
    //all done - log out!
    currentUser.logout();
}
Also used : IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException) Session(org.apache.shiro.session.Session) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 7 with Subject

use of org.apache.shiro.subject.Subject in project airpal by airbnb.

the class AirpalUserFactory method provide.

@Override
public AirpalUser provide() {
    Subject subject = SecurityUtils.getSubject();
    Object principal = subject.getPrincipal();
    if (principal instanceof ToAirpalUser) {
        return ((ToAirpalUser) principal).toAirpalUser(subject);
    } else if (principal instanceof String) {
        return new AirpalUserImpl((String) principal, defaultSchema, defaultQueryTimeout, defaultAccessLevel, subject);
    } else if (principal instanceof AirpalUser) {
        return (AirpalUser) principal;
    } else {
        throw new IllegalArgumentException(format("Could not marshall %s to AirpalUser", principal));
    }
}
Also used : Subject(org.apache.shiro.subject.Subject)

Example 8 with Subject

use of org.apache.shiro.subject.Subject in project airpal by airbnb.

the class SessionResource method doLogin.

@POST
@Path("/login")
public void doLogin(@Context HttpServletRequest request, @Context HttpServletResponse response, @FormParam("username") String username, @FormParam("password") String password) throws IOException {
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        currentUser.login(token);
    }
    WebUtils.redirectToSavedRequest(request, response, "/app");
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 9 with Subject

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

the class SecurityResource method getCurrentUserSubject.

@TimedResource
@GET
@Path("/subject")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Get user information", response = SubjectJson.class)
@ApiResponses(value = {})
public Response getCurrentUserSubject(@javax.ws.rs.core.Context final HttpServletRequest request) {
    final Subject subject = SecurityUtils.getSubject();
    final SubjectJson subjectJson = new SubjectJson(subject);
    return Response.status(Status.OK).entity(subjectJson).build();
}
Also used : SubjectJson(org.killbill.billing.jaxrs.json.SubjectJson) Subject(org.apache.shiro.subject.Subject) Path(javax.ws.rs.Path) TimedResource(org.killbill.commons.metrics.TimedResource) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 10 with Subject

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

the class ShiroSecurityProcessor method applySecurityPolicy.

private void applySecurityPolicy(Exchange exchange) throws Exception {
    ByteSource encryptedToken;
    // if we have username and password as headers then use them to create a token
    String username = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME, String.class);
    String password = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD, String.class);
    if (username != null && password != null) {
        ShiroSecurityToken token = new ShiroSecurityToken(username, password);
        // store the token as header, either as base64 or as the object as-is
        if (policy.isBase64()) {
            ByteSource bytes = ShiroSecurityHelper.encrypt(token, policy.getPassPhrase(), policy.getCipherService());
            String base64 = bytes.toBase64();
            exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, base64);
        } else {
            exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, token);
        }
        // and now remove the headers as we turned those into the token instead
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME);
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD);
    }
    Object token = ExchangeHelper.getMandatoryHeader(exchange, ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, Object.class);
    // we support the token in a number of ways
    if (token instanceof ShiroSecurityToken) {
        ShiroSecurityToken sst = (ShiroSecurityToken) token;
        encryptedToken = ShiroSecurityHelper.encrypt(sst, policy.getPassPhrase(), policy.getCipherService());
        // Remove unencrypted token + replace with an encrypted token
        exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN);
        exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, encryptedToken);
    } else if (token instanceof String) {
        String data = (String) token;
        if (policy.isBase64()) {
            byte[] bytes = Base64.decode(data);
            encryptedToken = ByteSource.Util.bytes(bytes);
        } else {
            encryptedToken = ByteSource.Util.bytes(data);
        }
    } else if (token instanceof ByteSource) {
        encryptedToken = (ByteSource) token;
    } else {
        throw new CamelExchangeException("Shiro security header " + ShiroSecurityConstants.SHIRO_SECURITY_TOKEN + " is unsupported type: " + ObjectHelper.classCanonicalName(token), exchange);
    }
    ByteSource decryptedToken = policy.getCipherService().decrypt(encryptedToken.getBytes(), policy.getPassPhrase());
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedToken.getBytes());
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    ShiroSecurityToken securityToken;
    try {
        securityToken = (ShiroSecurityToken) objectInputStream.readObject();
    } finally {
        IOHelper.close(objectInputStream, byteArrayInputStream);
    }
    Subject currentUser = SecurityUtils.getSubject();
    // Authenticate user if not authenticated
    try {
        authenticateUser(currentUser, securityToken);
        // Test whether user's role is authorized to perform functions in the permissions list
        authorizeUser(currentUser, exchange);
    } finally {
        if (policy.isAlwaysReauthenticate()) {
            currentUser.logout();
        }
    }
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteSource(org.apache.shiro.util.ByteSource) Subject(org.apache.shiro.subject.Subject) ObjectInputStream(java.io.ObjectInputStream)

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