2014-12-02 6 views
0

Я реализовал весеннюю безопасность 3.2.5, но, к сожалению, @PreAuthorize не работает над классами и методами. Когда я прочитал из документации, @PreAuthorize должен позволить методам и классам работать, если пользователь указал роль внутри аннотации, но я могу запускать все методы или классы без какой-либо разницы ролей. Вы можете увидеть security-config.xml и security.context.xml и мой класс, где я объявил аннотацию @PreAuthorize ниже. Я был бы рад, если бы вы помогли мне в решении этой проблемы.@PreAuthorize не работает на Spring

безопасности config.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans 
xmlns="http://www.springframework.org/schema/security" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:beans="http://www.springframework.org/schema/beans" 
xsi:schemaLocation=" 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-3.2.xsd 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> 

<http pattern="/securityNone" security="none" /> 

<http use-expressions="true"> 
    <intercept-url pattern="/**" access="isAuthenticated()" /> 
    <http-basic /> 
</http> 
<global-method-security pre-post-annotations="enabled" /> 


<authentication-manager> 
    <authentication-provider> 
     <user-service> 
      <user name="alperk" password="123" authorities="ROLE_USER" /> 
     </user-service> 
    </authentication-provider> 
</authentication-manager> 

безопасности context.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:sec="http://www.springframework.org/schema/security" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans /spring-beans-3.1.xsd 
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 

<bean id="defaultAuthEventPublisher"  class="org.springframework.security.authentication.DefaultAuthenticationEventPublisher"/> 

<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager"> 
    <property name="providers"> 
     <list> 
      <ref bean="authenticationProvider"/> 
     </list> 
    </property> 
    <property name="authenticationEventPublisher" ref="defaultAuthEventPublisher"/> 
</bean> 
<!-- Authentication service reference --> 
<bean id="customUserDetailsService" class="tr.com.sistek.utak.authentication.AuthenticationUserDetailsService"/> 

<!-- Authentication yapilirken MD5 password sifreleme kullaniliyor --> 
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/> 

<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> 
    <property name="userDetailsService" ref="customUserDetailsService"/> 
    <!--<property name="passwordEncoder" ref="passwordEncoder"/>--> 
</bean> 

<bean id="authenticationSuccessHandler" class="tr.com.sistek.utak.authentication.CustomAuthenticationSuccessHandler"> 
    <property name="defaultTargetUrl" value="/faces/private/MainMenu.jsf"/> 
</bean> 

<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler"> 
    <property name="exceptionMappings"> 
     <props> 
      <prop key="org.springframework.security.authentication.BadCredentialsException">/login-failure.jsf?err=HATALI_PWD</prop> 
      <prop key="org.springframework.security.authentication.CredentialsExpiredException">/change-password.jsf</prop> 
      <prop key="org.springframework.security.authentication.LockedException">/login-failure.jsf?err=HESAP_KILITLI</prop> 
      <prop key="org.springframework.security.authentication.DisabledException">/login-failure.jsf?err=HESAP_PASIF</prop> 
     </props> 
    </property> 
</bean> 

<bean id="accessDeniedHandler" class="org.springframework.security.web.access.AccessDeniedHandlerImpl"> 
    <property name="errorPage" value="/error401.jsf"/> 
</bean> 

<!-- Login Esnasinda Girilen Bilgileri Kontrol Etmek Icin Kullanilmistir --> 
<bean id="customPreAuthenticationLoginHandler" class="tr.com.sistek.utak.authentication.CustomPreAuthenticationLoginHandler"> 
    <property name="authenticationManager" ref="authenticationManager" /> 
    <property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" /> 
    <property name="authenticationFailureHandler" ref="authenticationFailureHandler" /> 
    <property name="filterProcessesUrl" value="/j_security_check" /> 

    <property name="sessionAuthenticationStrategy" ref="sas" /> 

    <property name="postOnly" value="false" /> 
</bean> 

<sec:http pattern="/assets/**" security="none"/> 
<sec:http pattern="/images/**" security="none"/> 
<sec:http pattern="/resources/**" security="none"/> 
<sec:http pattern="/themes/**" security="none"/> 
<sec:http pattern="/javax.faces.resource/**" security="none"/> 

<sec:global-method-security    
    pre-post-annotations="enabled" 
    mode="aspectj" 
    proxy-target-class="true"> 
</sec:global-method-security> 


<sec:http auto-config="true" use-expressions="true" 
      authentication-manager-ref="authenticationManager"> 


    <sec:intercept-url pattern="/dashboard/**" access="isAuthenticated()"/> 
    <sec:custom-filter before="FORM_LOGIN_FILTER" ref="customPreAuthenticationLoginHandler"/> 

    <sec:form-login login-page="/login.jsf" 
        authentication-failure-handler-ref = "authenticationFailureHandler" 
        default-target-url="/faces/private/MainMenu.jsf"/> 

    <sec:access-denied-handler ref = "accessDeniedHandler"/> 

    <sec:logout invalidate-session="true" 
       logout-success-url="/login.jsf" 
       logout-url="/logout"/> 

    <sec:session-management invalid-session-url="/login.jsf" session-authentication-strategy-ref="sas"/> 

    <sec:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" /> 

</sec:http> 


<bean id="jsfRedirectStrategy" class="tr.com.sistek.utak.jsf.filter.JsfRedirectStrategy"/> 

<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/> 

<!-- Authentication logout handler --> 
<bean id="customAuthenticationLogoutHandler" class="tr.com.sistek.utak.authentication.CustomAuthenticationLogoutHandler"/> 

<!-- ******************************************************************* --> 
<!-- Concurrent Session Management Configuration--> 
<!-- ******************************************************************* --> 
<bean id="concurrencyFilter" 
     class="org.springframework.security.web.session.ConcurrentSessionFilter"> 
    <property name="sessionRegistry" ref="sessionRegistry" /> 
    <property name="expiredUrl" value="/session-expired.jsf" /> 
    <!-- this permits redirection to session timeout page from javascript/ajax or http --> 
    <property name="redirectStrategy" ref="jsfRedirectStrategy" /> 
</bean> 

<bean id="sas" class= "org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy"> 
    <constructor-arg name="sessionRegistry" ref="sessionRegistry" /> 
    <property name="maximumSessions" value="1" /> 
    <!--  <property name="alwaysCreateSession" value="true" /> 
    <property name="exceptionIfMaximumExceeded" value="true" />--> 
</bean> 

<bean id="sessionRegistry" 
     class="org.springframework.security.core.session.SessionRegistryImpl" /> 

Bean:

@ManagedBean 
@ViewScoped 
@PreAuthorize("hasRole('ROLE_ADMIN')") 
public class OrderDetView implements Serializable { 

......

+0

Как вы ссылаетесь на методы в OrderDetView – 6ton

ответ

0

Это только моя первая мысль:

аннотации @ManagedBean и @ViewScoped показывают, что вы используете JSF Framework и, возможно, ваши OrderDetView боба ин просто JSF фасоль, но не Весенний боб. Но @PreAuthorize работает только для фасоли весны.

+0

Точно Ральф. Извините за мою ошибку. Я меняю свой вопрос прямо сейчас. Можно ли использовать @PreAuthorize в компоненте JSF (думаю, я не просил его убедиться) или преобразовать его в использование такой метадологии? Я был бы очень рад, если бы вы помогли мне – user2307786

+1

. Вы можете заставить его работать для любого класса, но для этого требуется AspectJ и компиляция во времени аспектов безопасности. –

+0

Hello Deinum. Как я понимаю из вашей позиции, вы говорите, что используете AspectJ с JSF Managed Bean, не преобразовывая свой компонент в Spring Managed Bean. Можете ли вы предоставить образец для использования AspectJ для управляемого компонента Jsf? – user2307786

Смежные вопросы