秒:授权不起作用

Posted

技术标签:

【中文标题】秒:授权不起作用【英文标题】:sec:authorize doesn't work 【发布时间】:2015-08-09 07:29:15 【问题描述】:

最近开始了一个新项目,决定使用最新版本的spring、spring security和thymeleaf 我已经包含了这些数据包

def springVersion = '4.1.6.RELEASE'
def securityVersion = '4.0.1.RELEASE'
def thymeleafVersion = '2.1.2.RELEASE'

compile "org.springframework:spring-core:$springVersion"
compile "org.springframework:spring-webmvc:$springVersion"
compile "org.springframework.security:spring-security-web:$securityVersion"
compile "org.springframework.security:spring-security-config:$securityVersion"

compile "org.thymeleaf:thymeleaf-spring4:$thymeleafVersion"
compile "org.thymeleaf.extras:thymeleaf-extras-springsecurity4:$thymeleafVersion"

我已将@EnableWebSecurity@Bean SpringSecurityDialect 添加到我的配置中。 在 layout.html 我有

<ul class="nav navbar-nav navbar-right">
        <li sec:authorize="isAnonymous()"><a th:href="@/login">Login</a></li>
        <li sec:authorize="isAuthenticated()"><a th:href="@/logout">Logout</a></li>
    </ul>
<br>

两个选项都没有出现。此外,当我用true 替换这些调用时,这并没有改变任何东西。当函数名称出现错误时,我看不到任何错误消息,例如isAnon()。 我错过了什么吗?

UPD 安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
  

  @Override
  protected void configure(HttpSecurity http) throws Exception 
    http
      .csrf().disable()
      .formLogin()
        .loginPage("/login")
        .failureUrl("/login-error")
    .and()
      .logout()
        .logoutSuccessUrl("/")
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
  

网络配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "stats.web.controller","stats.web.domain","stats.mapper", "stats.core.service;")
@Import( WebSecurityConfig.class )
public class WebConfig extends WebMvcConfigurerAdapter 

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) 
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
  

  @Override
  public void addInterceptors(InterceptorRegistry registry) 

    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    registry.addInterceptor(localeChangeInterceptor);
  

  @Bean
  public LocaleResolver localeResolver() 

    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
    cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en"));
    return cookieLocaleResolver;
  

  @Bean
  public ServletContextTemplateResolver templateResolver() 
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setCacheable(false);
    resolver.setCharacterEncoding("UTF-8");
    return resolver;

  

  public SpringTemplateEngine templateEngine() 
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.addDialect(securityDialect());
    engine.setTemplateResolver(templateResolver());
    return engine;
  


  @Bean
  public SpringSecurityDialect securityDialect() 
    return new SpringSecurityDialect();
  


  @Bean
  public ViewResolver viewResolver() 

    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setOrder(1);
    viewResolver.setViewNames(new String[]"*");
    viewResolver.setCache(false);
    viewResolver.setCharacterEncoding("UTF-8");
    return viewResolver;
  

  @Bean
  public MessageSource messageSource() 

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");    
    messageSource.setUseCodeAsDefaultMessage(true);
    messageSource.setDefaultEncoding("UTF-8");
    messageSource.setCacheSeconds(0);
    return messageSource;
  

不确定需要哪些引导类,但我检查了页面,应该有登录链接的第二个ul 是空的:

<ul class="nav navbar-nav">
    ::before
    <li>...</li>
    <li>...</li>
    <li>...</li>
    ::after

</ul>
<ul class="nav navbar-nav navbar-right">
    ::before
    ::after
</ul>

【问题讨论】:

如果您不将其连接到引擎,则仅添加方言不会有太大作用。 我连接它,我在日志中看到这条消息 [THYMELEAF] * Dialect [2 of 2]: org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect 请添加配置和引导类。 @M.Deinum 如果您还需要引导类,请告诉我 对于初学者来说,用@Bean注释你的templateEngine 【参考方案1】:

这是我所说的 XML 配置。请删除您拥有的文件,将您的方法注释到@Service,@Repository 用于 DAO,@Controller 用于控制器,@Entity 用于模型。请不要忘记@Transactional。我正在对 postgreSQL 中的数据库进行身份验证,但您可以更改方言。

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"
        >
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml,/WEB-INF/spring/appServlet/security-applicationContext.xml</param-value>
    </context-param>

    <session-config>
        <session-timeout>1440</session-timeout>
    </session-config>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>403Jsp</servlet-name>
        <jsp-file>/WEB-INF/views/error/403.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>403Jsp</servlet-name>
        <url-pattern>/403</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
     <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Servlet-context.xml:

    <security:global-method-security
            secured-annotations="enabled"
            jsr250-annotations="disabled"
            pre-post-annotations="enabled"/>

    <context:component-scan base-package="com.journaldev.spring" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <context:property-placeholder location="classpath:application.properties"/>

    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <beans:bean class="org.springframework.mobile.device.DeviceWebArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>
    <mvc:interceptors>
        <beans:bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor"/>
        <beans:ref bean="localeChangeInterceptor" />
    </mvc:interceptors>

    <mvc:default-servlet-handler/>

    <resources mapping="/resources/" location="/resources/"/>

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>

<!-- If you have locale and all, then you need code below -->
    <!-- locale -->
    <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:/locale/messages"/>
        <beans:property name="defaultEncoding" value="UTF-8"/>
    </beans:bean>


    <!-- default locale -->
    <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <beans:property name="defaultLocale" value="de"/>
    </beans:bean>

    <!-- Change locale via url. -->
    <beans:bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <beans:property name="paramName" value="lang"/>
    </beans:bean>

    <beans:bean id="handlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <beans:property name="interceptors">
            <beans:list>
                <beans:ref bean="localeChangeInterceptor"/>
            </beans:list>
        </beans:property>
    </beans:bean>
</beans:beans>

根上下文.xml:

 <context:component-scan base-package="com.journaldev.spring">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <context:property-placeholder location="classpath:application.properties"/>

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
                destroy-method="close">
        <beans:property name="driverClassName" value="org.postgresql.Driver"/>
        <beans:property name="url"
                        value="jdbc:postgresql://localhost:5432/dbname"/>
        <beans:property name="username" value="postgres"/>
        <beans:property name="password" value="dbpass"/>
        <beans:property name="removeAbandoned" value="true"/>
        <beans:property name="removeAbandonedTimeout" value="20"/>
        <beans:property name="defaultAutoCommit" value="false"/>
    </beans:bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="packagesToScan" value="com.journaldev.spring.model" />

        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</beans:prop>
                <beans:prop key="hibernate.show_sql">false</beans:prop>
                <!--   <beans:prop key="hibernate.jdbc.batch_size">1000</beans:prop>
                   <beans:prop key="hibernate.order_updates">true</beans:prop>-->
                <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

    <beans:bean id="LoginServiceImpl" class="com.journaldev.spring.service.LoginServiceImpl"/>

    <task:annotation-driven/>

    <tx:annotation-driven transaction-manager="transactionManager"/>

        <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
        </beans:bean>
</beans:beans>

security-applicationContext.xml:

<security:http pattern="/resources/**" security="none"/>

<security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
    <security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/dashboard" always-use-default-target="false" authentication-failure-url="/denied" />
    <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
    <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<security:port-mappings>
    <security:port-mapping http="80" https="443"/>
</security:port-mappings>
<security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

 <security:session-management session-fixation-protection="migrateSession">
     <security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="5" expired-url="/login"/>
 </security:session-management>
</security:http>

<!-- Rest authentication, don't edit, delete, add-->
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">

<security:filter-chain-map path-type="ant">
    <security:filter-chain filters="persistencefilter,authenticationfilter" pattern="/login"/>
    <security:filter-chain filters="persistencefilter,logoutfilter" pattern="/logout"/>
    <security:filter-chain pattern="/rest/**" filters="persistencefilter,restfilter" />
</security:filter-chain-map>
</bean>

<bean id="persistencefilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

<bean id="authenticationfilter" class="com.journaldev.spring.utility.AuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
    <property name="passwordParameter" value="pass"/>
    <property name="usernameParameter" value="user"/>
    <property name="postOnly" value="false"/>
</bean>

<bean id="myAuthSuccessHandler" class="com.journaldev.spring.utility.AuthenticationSuccessHandler"/>

<bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>

<bean id="logoutfilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">

    <constructor-arg index="0" value="/"/>
    <constructor-arg index="1">
        <list>
            <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
                <property name="invalidateHttpSession" value="true"/>
                <property name="clearAuthentication" value="true"/>
            </bean>
            <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
        </list>
    </constructor-arg>
</bean>

<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
    <property name="allowIfAllAbstainDecisions" value="false"/>
    <property name="decisionVoters">
        <list>
            <ref bean="roleVoter"/>
        </list>
    </property>
</bean>

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

<bean id="restfilter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
    <property name="securityMetadataSource">
        <security:filter-invocation-definition-source>
            <security:intercept-url pattern="/rest/**" access="ROLE_USER"/>
        </security:filter-invocation-definition-source>
    </property>
</bean>
<!-- Rest authentication ends here-->

<!-- queries to be run on data -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
    <beans:property name="key" value="_spring_security_remember_me" />
    <property name="alwaysRemember" value="true"/>
    <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
    <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
</beans:bean>

<!--Database management for remember-me -->
<beans:bean id="jdbcTokenRepository"
            class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
    <beans:property name="createTableOnStartup" value="false"/>
    <beans:property name="dataSource" ref="dataSource" />
</beans:bean>

<!-- Remember me ends here -->
<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider user-service-ref="LoginServiceImpl">
       <security:password-encoder  ref="encoder"/>
    </security:authentication-provider>
</security:authentication-manager>

<beans:bean id="encoder"
            class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <beans:constructor-arg name="strength" value="11" />
</beans:bean>
    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>
</beans>

供您参考:我为登录明确声明的唯一 bean LoginServiceImpl bean:

@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException 
        Person person = personDAO.findPersonByUsername(username.toLowerCase());
            if(person == null)  throw new UsernameNotFoundException("Wrong username or password");
        return assembler.buildUserFromUserEntity(person);
    

    public LoginServiceImpl() 
    

要使用我的代码,你需要添加xml文件,我希望你可以自己添加架构映射,如果没有,我会粘贴它们。在 XML 文件中创建和添加代码完成后,请将包名更正为 LoginServiceImpl,并在 web.xml 中正确指向 security-applicationContext.xml 和 root-context.xml。

任何你需要的帮助都让我知道。上面的配置是由 M.Denium 调整的,所以如果我周末旅行时不在,他有空,他可以帮助你。玩得开心。 :-)

【讨论】:

还在上下文中写下正确的包名称:组件扫描...有关我的配置和 M.Deniums 答案的更多信息可以在这里找到:***.com/questions/30399338/… 我在你的配置中看到了 use-expressions。据我了解,它们在使用 authorizeRequests 时会自动启用。我尝试使用http.authorizeRequests().anyRequest().permitAll();,但仍然没有运气。 我不知道如何进行 Java 配置。但是,您可以使用上述配置。这就是我发布它的原因。我没有假设比较。 是的,我今天晚些时候试试,但我也想找到问题的根源。【参考方案2】:

将您的配置与Spring Boot autoconfiguration for Thymeleaf 进行比较可能会有所帮助。

另外,我隐约记得有类似的问题,我通过将sec:authorize 移动到&lt;ul&gt;(而不是&lt;li&gt;)来解决。已经有一段时间了,所以我不记得我这样移动它的原因。 (对不起!)这是一个对我有用的示例(尽管它与 org.thymeleaf.extras:thymeleaf-extras-springsecurity3 一起使用)。

<ul sec:authorize="isAuthenticated()">
   <li><p><span sec:authentication="name">test</span></p> </li>
   <li><a href="logout.html " th:href="@/logout">Logout</a> </li>
</ul>
<ul sec:authorize="isAnonymous()">
   <li><a href="signup.html" th:href="@/signup">Sign Up</a> </li>
   <li><a href="login.html " th:href="@/login">Login</a> </li>
</ul>

【讨论】:

比较配置似乎是个好主意,谢谢!我自己有一个 spring3 项目,这个项目有效,但是将这个项目降级到第三个版本并没有帮助。也没有将 sec 移动到 ul 标签。【参考方案3】:

最后,我发现了我工作的 spring 3 项目的不同之处。不是春季版,是这个缺课

public class SpringSecurityInitializer extends
    AbstractSecurityWebApplicationInitializer 


添加后,“sec”属性正常工作。

【讨论】:

以上是关于秒:授权不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Laravel Gate:授权不起作用

由于CORS,角度授权不起作用[重复]

自定义授权属性在 WebAPI 中不起作用

春季安全。授权在jsp上不起作用

IOS 8 CLLocationManager 问题(授权不起作用)

从前端发送的授权令牌不起作用(JWT)