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();
}
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));
}
}
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");
}
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();
}
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();
}
}
}
Aggregations