3

質問: JavaEE6 の実装はどこにありますか?

私は現在 JavaEE6 プロジェクトに取り組んでおり、ドキュメントに基づいて web.xml と shiro.ini を既に構成しているにもかかわらず、Shiro の注釈がそのままでは機能しないことがわかりました。

これは私が持っているものです:

1.) ページ:

<h:form>
  <h:commandLink action="#{userBean.action1()}" value="Action 1"></h:commandLink>
</h:form>

2.) バッキングビーン:

@Stateless
@Named
public class UserBean {
    @Inject
    private Logger log;

    @RequiresAuthentication
    public void action1() {
        log.debug("action.1");
    }
}

3.) web.xml

<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4.) shiro.ini

[main]
# listener = org.apache.shiro.config.event.LoggingBeanListener

shiro.loginUrl = /login.xhtml

[users]
# format: username = password, role1, role2, ..., roleN
root = secret,admin
guest = guest,guest
presidentskroob = 12345,president
darkhelmet = ludicrousspeed,darklord,schwartz
lonestarr = vespa,goodguy,schwartz

[roles]
# format: roleName = permission1, permission2, ..., permissionN
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

[urls]
# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
# the 'authc' filter must still be specified for it so it can process that url's
# login submissions. It is 'smart' enough to allow those requests through as specified by the
# shiro.loginUrl above.
/login.xhtml = authc
/logout = logout
/account/** = authc
/remoting/** = authc, roles[b2bClient], perms["remote:invoke:lan,wan"]

しかし、ボタンをクリックすると、まだアクションが実行されます。無許可の例外をスローする必要がありますか?他の shiro アノテーションについても同様です。

チェックを手動で実行すると、機能することに注意してください。

public void action1() {
    Subject currentUser = SecurityUtils.getSubject();
    AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
    currentUser.login(token);

    log.debug("user." + currentUser);
    if (currentUser.isAuthenticated()) {
        log.debug("action.1");
    } else {
        log.debug("not authenticated");
    }
}

ありがとう、
ツェツヤ

4

2 に答える 2

4

基本的に、呼び出された CDI および EJB メソッドのアノテーションをスキャンするには、 Java EE インターセプターが必要です。

まず、インターセプターがインターセプトする必要があるアノテーションを作成します。

@Inherited
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ShiroSecured {
    //
}

次に、インターセプター自体を作成します。

@Interceptor
@ShiroSecured
public class ShiroSecuredInterceptor implements Serializable {

    private static final long serialVersionUID = 1L;

    @AroundInvoke
    public Object interceptShiroSecurity(InvocationContext context) throws Exception {
        Class<?> c = context.getTarget().getClass();
        Method m = context.getMethod();
        Subject subject = SecurityUtils.getSubject();

        if (!subject.isAuthenticated() && hasAnnotation(c, m, RequiresAuthentication.class)) {
            throw new UnauthenticatedException("Authentication required");
        }

        if (subject.getPrincipal() != null && hasAnnotation(c, m, RequiresGuest.class)) {
            throw new UnauthenticatedException("Guest required");
        }

        if (subject.getPrincipal() == null && hasAnnotation(c, m, RequiresUser.class)) {
            throw new UnauthenticatedException("User required");
        }

        RequiresRoles roles = getAnnotation(c, m, RequiresRoles.class);

        if (roles != null) {
            subject.checkRoles(Arrays.asList(roles.value()));
        }

        RequiresPermissions permissions = getAnnotation(c, m, RequiresPermissions.class);

        if (permissions != null) {
             subject.checkPermissions(permissions.value());
        }

        return context.proceed();
    }

    private static boolean hasAnnotation(Class<?> c, Method m, Class<? extends Annotation> a) {
        return m.isAnnotationPresent(a)
            || c.isAnnotationPresent(a)
            || c.getSuperclass().isAnnotationPresent(a);
    }

    private static <A extends Annotation> A getAnnotation(Class<?> c, Method m, Class<A> a) {
        return m.isAnnotationPresent(a) ? m.getAnnotation(a)
            : c.isAnnotationPresent(a) ? c.getAnnotation(a)
            : c.getSuperclass().getAnnotation(a);
    }

}

注釈は、CDI が実際にはプロキシであり、Shiro の注釈が設定されていない場合、ターゲット クラスと同様に、ターゲット クラスのスーパークラスでチェックされることに注意してください@Inherited

CDI マネージド Bean で動作させるには、まず/WEB-INF/beans.xml次のようにインターセプターを登録します。

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd"
>
    <interceptors>
        <class>com.example.interceptor.ShiroSecuredInterceptor</class>
    </interceptors>
</beans>

同様に、EJB で動作させるには、まずインターセプター/WEB-INF/ejb-jar.xmlを次のように (または/META-INF/ejb-jar.xml、EAR に別の EJB プロジェクトがある場合は に)登録します。

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
    version="3.1"
>
    <interceptors>
        <interceptor>
            <interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
        </interceptor>
    </interceptors>
    <assembly-descriptor>
        <interceptor-binding>
            <ejb-name>*</ejb-name>
            <interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
        </interceptor-binding>
    </assembly-descriptor>
</ejb-jar>

@ShiroSecuredCDI マネージド Bean では、インターセプターを実行するためにカスタム アノテーションを設定する必要があります。

@Named
@RequestScoped
@ShiroSecured
public class SomeBean {

    @RequiresRoles("ADMIN")
    public void doSomethingWhichIsOnlyAllowedByADMIN() {
        // ...
    }

}

これは EJB では必要ありませんejb-jar.xml。すべての EJB にすでに登録されています。

以下も参照してください。

于 2013-01-23T12:01:52.717 に答える
-2

基本的に、Shiro の Requires* インターフェイスの実装が不足しているため、必要に応じて実装しました。興味のある方はこちらをご覧ください: http://czetsuya-tech.blogspot.com/2012/10/how-to-integrate-apache-shiro-with.html

于 2012-10-11T06:37:36.100 に答える