Search in sources :

Example 41 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class QuickStart method run.

public void run() {
    // get the current subject
    Subject subject = SecurityUtils.getSubject();
    // Subject is not authenticated yet
    Assert.isTrue(!subject.isAuthenticated());
    // login the subject with a username / password
    UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password");
    subject.login(token);
    // joe.coder has the "user" role
    subject.checkRole("user");
    // joe.coder does NOT have the admin role
    Assert.isTrue(!subject.hasRole("admin"));
    // joe.coder has the "read" permission
    subject.checkPermission("read");
    // current user is allowed to execute this method.
    simpleService.readRestrictedCall();
    try {
        // but not this one!
        simpleService.writeRestrictedCall();
    } catch (AuthorizationException e) {
        log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'");
    }
    // logout
    subject.logout();
    Assert.isTrue(!subject.isAuthenticated());
}
Also used : AuthorizationException(org.apache.shiro.authz.AuthorizationException) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 42 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project killbill by killbill.

the class TestKillbillJdbcTenantRealm method testAuthentication.

@Test(groups = "slow")
public void testAuthentication() throws Exception {
    final DelegatingSubject subject = new DelegatingSubject(securityManager);
    // Good combo
    final AuthenticationToken goodToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret());
    try {
        securityManager.login(subject, goodToken);
        Assert.assertTrue(true);
    } catch (final AuthenticationException e) {
        Assert.fail();
    }
    // Bad login
    final AuthenticationToken badPasswordToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret() + "T");
    try {
        securityManager.login(subject, badPasswordToken);
        Assert.fail();
    } catch (final AuthenticationException e) {
        Assert.assertTrue(true);
    }
    // Bad password
    final AuthenticationToken badLoginToken = new UsernamePasswordToken(tenant.getApiKey() + "U", tenant.getApiSecret());
    try {
        securityManager.login(subject, badLoginToken);
        Assert.fail();
    } catch (final AuthenticationException e) {
        Assert.assertTrue(true);
    }
}
Also used : DelegatingSubject(org.apache.shiro.subject.support.DelegatingSubject) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Example 43 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project killbill by killbill.

the class KillBillAuth0Realm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException {
    if (token instanceof UsernamePasswordToken) {
        final UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        if (doAuthenticate(upToken)) {
            // Credentials are valid
            return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
        }
    } else {
        final String bearerToken = (String) token.getPrincipal();
        final Claims claims = verifyJWT(bearerToken);
        // Credentials are valid
        // This config must match the one in Kaui
        final Object principal = claims.get(securityConfig.getShiroAuth0UsernameClaim());
        // For the JWT to contains the permissions, the `Add Permissions in the Access Token` setting must be turned on in Auth0
        if (claims.containsKey("permissions") && claims.get("permissions") instanceof Iterable) {
            // In order to use the permissions from the JWT (and avoid calling Auth0 later on), we need to eagerly cache them,
            // as doGetAuthorizationInfo won't have access to the token
            final org.apache.shiro.cache.Cache<Object, AuthorizationInfo> authorizationCache = getAuthorizationCache();
            // Should never be null (initialized via init())
            if (authorizationCache != null) {
                final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(null);
                final Set<String> permissions = new HashSet<String>();
                for (final Object permission : (Iterable) claims.get("permissions")) {
                    permissions.add(permission.toString());
                }
                simpleAuthorizationInfo.setStringPermissions(permissions);
                final MutablePrincipalCollection principals = new SimplePrincipalCollection();
                principals.add(principal, getName());
                final Object authorizationCacheKey = getAuthorizationCacheKey(principals);
                authorizationCache.put(authorizationCacheKey, simpleAuthorizationInfo);
            }
        }
        return new SimpleAuthenticationInfo(principal, token.getCredentials(), getName());
    }
    throw new AuthenticationException("Auth0 authentication failed");
}
Also used : Claims(io.jsonwebtoken.Claims) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) AuthorizationInfo(org.apache.shiro.authz.AuthorizationInfo) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) MutablePrincipalCollection(org.apache.shiro.subject.MutablePrincipalCollection) HashSet(java.util.HashSet)

Example 44 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project killbill by killbill.

the class TestKillBillJdbcRealm method testAuthorization.

@Test(groups = "slow")
public void testAuthorization() throws SecurityApiException {
    final String username = "i like";
    final String password = "c0ff33";
    securityApi.addRoleDefinition("restricted", ImmutableList.of("account:*", "invoice", "tag:create_tag_definition"), callContext);
    securityApi.addUserRoles(username, password, ImmutableList.of("restricted"), callContext);
    final AuthenticationToken goodToken = new UsernamePasswordToken(username, password);
    final Subject subject = securityManager.login(null, goodToken);
    subject.checkPermission(Permission.ACCOUNT_CAN_CHARGE.toString());
    subject.checkPermission(Permission.INVOICE_CAN_CREDIT.toString());
    subject.checkPermission(Permission.TAG_CAN_CREATE_TAG_DEFINITION.toString());
    try {
        subject.checkPermission(Permission.TAG_CAN_DELETE_TAG_DEFINITION.toString());
        Assert.fail("Subject should not have rights to delete tag definitions");
    } catch (AuthorizationException e) {
    }
    subject.logout();
    securityApi.addRoleDefinition("newRestricted", ImmutableList.of("account:*", "invoice", "tag:delete_tag_definition"), callContext);
    securityApi.updateUserRoles(username, ImmutableList.of("newRestricted"), callContext);
    final Subject newSubject = securityManager.login(null, goodToken);
    newSubject.checkPermission(Permission.ACCOUNT_CAN_CHARGE.toString());
    newSubject.checkPermission(Permission.INVOICE_CAN_CREDIT.toString());
    newSubject.checkPermission(Permission.TAG_CAN_DELETE_TAG_DEFINITION.toString());
    try {
        newSubject.checkPermission(Permission.TAG_CAN_CREATE_TAG_DEFINITION.toString());
        Assert.fail("Subject should not have rights to create tag definitions");
    } catch (AuthorizationException e) {
    }
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthorizationException(org.apache.shiro.authz.AuthorizationException) DelegatingSubject(org.apache.shiro.subject.support.DelegatingSubject) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Example 45 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project killbill by killbill.

the class TestKillBillJdbcRealm method testAuthorizationV3.

@Test(groups = "slow", description = "Check group:* behavior with custom permissions")
public void testAuthorizationV3() throws SecurityApiException {
    securityApi.addRoleDefinition("for another user", ImmutableList.of("acme:kb_dev"), callContext);
    final String username = "i like";
    final String password = "c0ff33";
    final String role = "for this user";
    securityApi.addRoleDefinition(role, ImmutableList.of("account", "invoice:*", "tag:create_tag_definition", "acme:*"), callContext);
    securityApi.addUserRoles(username, password, ImmutableList.of(role), callContext);
    final AuthenticationToken goodToken = new UsernamePasswordToken(username, password);
    final Subject subject = securityManager.login(null, goodToken);
    try {
        ThreadContext.bind(subject);
        subject.checkPermission(Permission.ACCOUNT_CAN_CHARGE.toString());
        subject.checkPermission(Permission.INVOICE_CAN_CREDIT.toString());
        subject.checkPermission(Permission.TAG_CAN_CREATE_TAG_DEFINITION.toString());
        subject.checkPermission("acme:kb_dev");
        final Object[] rolePermissions = ImmutableList.of("account:*", "invoice:*", "tag:create_tag_definition", "acme:*").toArray();
        // "*" is not expanded
        final List<String> roleDefinitions = securityApi.getRoleDefinition(role, callContext);
        Assert.assertEqualsNoOrder(roleDefinitions.toArray(), rolePermissions);
        // "*" is not expanded
        final Set<String> permissions = securityApi.getCurrentUserPermissions(callContext);
        Assert.assertEqualsNoOrder(permissions.toArray(), rolePermissions);
        securityApi.addRoleDefinition("for yet another user", ImmutableList.of("acme:kb_deployer"), callContext);
        // "*" is not expanded
        final List<String> roleDefinitions2 = securityApi.getRoleDefinition(role, callContext);
        Assert.assertEqualsNoOrder(roleDefinitions2.toArray(), rolePermissions);
        // "*" is not expanded
        final Set<String> permissions2 = securityApi.getCurrentUserPermissions(callContext);
        Assert.assertEqualsNoOrder(permissions2.toArray(), rolePermissions);
    } finally {
        ThreadContext.unbindSubject();
        subject.logout();
    }
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) DelegatingSubject(org.apache.shiro.subject.support.DelegatingSubject) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Aggregations

UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)114 Subject (org.apache.shiro.subject.Subject)50 Test (org.junit.Test)30 AuthenticationException (org.apache.shiro.authc.AuthenticationException)28 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)27 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)17 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 Test (org.testng.annotations.Test)11 LockedAccountException (org.apache.shiro.authc.LockedAccountException)10 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)9 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)7 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)7 Session (org.apache.shiro.session.Session)6 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)4 AbstractQi4jTest (org.qi4j.test.AbstractQi4jTest)4