Search in sources :

Example 6 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project shiro by apache.

the class JdbcRealm method doGetAuthorizationInfo.

/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // null usernames are invalid
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }
    String username = (String) getAvailablePrincipal(principals);
    Connection conn = null;
    Set<String> roleNames = null;
    Set<String> permissions = null;
    try {
        conn = dataSource.getConnection();
        // Retrieve roles and permissions from database
        roleNames = getRoleNamesForUser(conn, username);
        if (permissionsLookupEnabled) {
            permissions = getPermissions(conn, username, roleNames);
        }
    } catch (SQLException e) {
        final String message = "There was a SQL error while authorizing user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }
        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;
}
Also used : SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) AuthorizationException(org.apache.shiro.authz.AuthorizationException) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Example 7 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project shiro by apache.

the class TextConfigurationRealmTest method testCheckRole.

/*
     * Tests that roles can't be checked while the realm is being loaded. 
     */
@Test
public void testCheckRole() throws InterruptedException {
    setUpForReadConfigurationTest();
    executeTest(new Runnable() {

        public void run() {
            PrincipalCollection principalCollection = new SimplePrincipalCollection("user1", "realm1");
            try {
                realm.checkRoles(principalCollection, new String[] { "role1", "role2" });
            } catch (AuthorizationException ae) {
                fail("principal doesn't have all roles when it should");
            }
        }
    });
}
Also used : AuthorizationException(org.apache.shiro.authz.AuthorizationException) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) Test(org.junit.Test)

Example 8 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException 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 9 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project killbill by killbill.

the class KillBillAuth0Realm method findAuth0UserId.

private String findAuth0UserId(final String username, final String token) {
    final String path;
    try {
        path = "/api/v2/users-by-email?email=" + URLEncoder.encode(username, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
        // Should never happen
        throw new IllegalStateException(e);
    }
    final Response auth0RawResponse = doGetRequest(path, token);
    try {
        final List<Map<String, Object>> auth0Response = mapper.readValue(auth0RawResponse.getResponseBodyAsStream(), new TypeReference<List<Map<String, Object>>>() {
        });
        if (auth0Response == null) {
            log.warn("Unable to find user {} in Auth0", username);
            return null;
        } else if (auth0Response.size() > 1) {
            log.warn("Too many users for {} in Auth0", username);
            return null;
        }
        return (String) auth0Response.get(0).get("user_id");
    } catch (final IOException e) {
        log.warn("Unable to read response from Auth0", e);
        throw new AuthorizationException(e);
    }
}
Also used : Response(org.asynchttpclient.Response) AuthorizationException(org.apache.shiro.authz.AuthorizationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) List(java.util.List) IOException(java.io.IOException) Map(java.util.Map)

Example 10 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project killbill by killbill.

the class KillBillAuth0Realm method getBearerToken.

private String getBearerToken() {
    final BoundRequestBuilder builder = httpClient.preparePost(securityConfig.getShiroAuth0Url() + "/oauth/token");
    builder.addFormParam("client_id", securityConfig.getShiroAuth0ClientId());
    builder.addFormParam("client_secret", securityConfig.getShiroAuth0ClientSecret());
    builder.addFormParam("audience", securityConfig.getShiroAuth0Url() + "/api/v2/");
    builder.addFormParam("grant_type", "client_credentials");
    builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
    final Response response;
    try {
        final ListenableFuture<Response> futureStatus = builder.execute(new AsyncCompletionHandler<Response>() {

            @Override
            public Response onCompleted(final Response response) throws Exception {
                return response;
            }
        });
        response = futureStatus.get(DEFAULT_TIMEOUT_SECS, TimeUnit.SECONDS);
    } catch (final TimeoutException toe) {
        log.warn("Timeout while connecting to Auth0", toe);
        throw new AuthenticationException(toe);
    } catch (final Exception e) {
        log.warn("Error while connecting to Auth0", e);
        throw new AuthenticationException(e);
    }
    final Map<String, Object> auth0Response;
    try {
        auth0Response = mapper.readValue(response.getResponseBodyAsStream(), new TypeReference<Map<String, Object>>() {
        });
    } catch (final Exception e) {
        log.warn("Unable to read response from Auth0", e);
        throw new AuthorizationException(e);
    }
    final Object accessToken = auth0Response.get("access_token");
    if (accessToken == null) {
        throw new AuthorizationException("Unable to generate Bearer token");
    }
    return (String) accessToken;
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) TimeoutException(java.util.concurrent.TimeoutException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SignatureException(io.jsonwebtoken.security.SignatureException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) JwtException(io.jsonwebtoken.JwtException) Response(org.asynchttpclient.Response) BoundRequestBuilder(org.asynchttpclient.BoundRequestBuilder) TypeReference(com.fasterxml.jackson.core.type.TypeReference) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

AuthorizationException (org.apache.shiro.authz.AuthorizationException)35 IOException (java.io.IOException)10 Map (java.util.Map)7 SimpleAuthorizationInfo (org.apache.shiro.authz.SimpleAuthorizationInfo)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 Response (org.asynchttpclient.Response)6 DataAccessRequest (org.obiba.mica.access.domain.DataAccessRequest)6 List (java.util.List)4 AuthenticationException (org.apache.shiro.authc.AuthenticationException)4 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)4 Permission (org.apache.shiro.authz.Permission)4 Subject (org.apache.shiro.subject.Subject)4 Timed (com.codahale.metrics.annotation.Timed)3 ParseException (java.text.ParseException)3 HashSet (java.util.HashSet)3 TimeoutException (java.util.concurrent.TimeoutException)3 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)3 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)3 BoundRequestBuilder (org.asynchttpclient.BoundRequestBuilder)3 Test (org.junit.Test)3