我正在我的项目中将Spring安全性从3.1升级到3.2.由于3.2支持基于代码的配置,因此我决定将旧的基于XML的配置转换为Java代码.
我收到异常说"authenticationManager"每次尝试启动应用程序时都没有找到带名字的bean .@EnableGlobalMethodSecurity注释添加到配置类后,此异常开始出现.
Spring框架版本:4.0.0.RELEASE
Spring安全版:3.2.0.RELEASE
旧的Xml配置看起来像这样:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security secured-annotations="enabled"
jsr250-annotations="enabled"
pre-post-annotations="enabled"
proxy-target-class="true"/>
<http auto-config="true" use-expressions="true" >
<form-login login-page="/login"
default-target-url="/home"
authentication-failure-url = "/login?login_error=1" />
<logout logout-url="/logout" logout-success-url="/index" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="authUserDetailService">
<password-encoder hash="plaintext"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
Run Code Online (Sandbox Code Playgroud)
新的Java配置类看起来像这样:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
@Bean
public UserDetailsService userDetailsServiceBean() …Run Code Online (Sandbox Code Playgroud) 我刚刚开始了一个新的春季项目,这次我想做"正确"的事情.在上一个项目中,由于多个@ComponentScan注释,我遇到了多个注册某些类的问题.(即所有服务类都注册了两次)
基本上我使用以下布局:
WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Run Code Online (Sandbox Code Playgroud)
RootConfig:
@Configuration
@ComponentScan
public class RootConfig {
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
WebMvcConfig:
@EnableWebMvc
@ComponentScan
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
DatabaseConfig:
@Configuration
@EnableJpaRepositories("my.base.class.path")
public …Run Code Online (Sandbox Code Playgroud) 我在春天写了一个小应用程序来学习java配置,因为我已经被同行唠叨了一段时间来升级我们的应用程序;-),一个简单的待办事项列表应用程序,它具有安全性和web mvc配置,JPA用于持久性,所有通过java配置.我在尝试运行应用程序时遇到了问题.scurity配置和JPA等工作正常但在成功拦截受保护的URL后我得到一个空视图
主Web应用程序初始化程序类扩展 AbstractAnnotationConfigDispatcherServletInitializer
public class WiggleWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { WiggleApplicationConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WiggleWebAppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected void registerDispatcherServlet(ServletContext servletContext) {
super.registerDispatcherServlet(servletContext);
servletContext.addListener(new HttpSessionEventPublisher());
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] { characterEncodingFilter };
}
}
Run Code Online (Sandbox Code Playgroud)
在WiggleApplicationConfig进口安全,JPA和社会
@Configuration …Run Code Online (Sandbox Code Playgroud) 我使用从xml-转换为Java-Config的Spring4/Hibernate4项目获得以下异常.
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
Run Code Online (Sandbox Code Playgroud)
该项目在Eclipse中启动属性和errorfree,但在第一个请求时出现Exception.在我ConfigRoot-class我已经@Bean配置为DataSource,SessionFactory,HibernateTransactionManager,ImprovedNamingStrategy.
我的所有@Service服务都注明了@Transactional.
知道这可能来自哪里?
编辑1
根据要求,这里是stacktrace:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
employees.service.PersonService.getAllInHierarchcalOrder(PersonService.java:58)
employees.controller.PersonController.getPersons(PersonController.java:64)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) … 使用纯Spring Java Config我很难让Spring和CAS执行单点注销.我有单点登录使用下面的配置.我使用一个简单的JSP页面对url https://nginx.shane.com/app/logout执行表单POST,并在POST'd数据中包含CSRF值.这一切似乎都没有错误,但是当我进入安全页面时,它只是让我回来而无需登录.有任何想法吗?
@Configuration
@EnableWebSecurity
public class SecurityWebAppConfig extends WebSecurityConfigurerAdapter {
@Bean
protected ServiceProperties serviceProperties() {
ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setService("https://nginx.shane.com/app/j_spring_cas_security_check");
serviceProperties.setSendRenew(false);
return serviceProperties;
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(authenticationUserDetailsService());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey("an_id_for_this_auth_provider_only");
return casAuthenticationProvider;
}
@Bean
public AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService() {
return new TestCasAuthenticationUserDetailsService();
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator("https://nginx.shane.com/cas");
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
return casAuthenticationFilter;
}
@Bean …Run Code Online (Sandbox Code Playgroud) 有没有办法在不使用 spring boot 的情况下在普通 spring web mvc 应用程序中启用 yaml 配置(而不是属性文件)并支持 @Value 注释。
我搜索了很多,到处都使用弹簧靴。我对使用 spring boot 不感兴趣,因为它非常重,并且为自动设置配置了许多依赖项。
任何帮助,将不胜感激......
我的Spring Batch信息库(部署在Oracle数据库上)位于不同的架构中,因此我需要在架构名称前加上前缀。
使用XML配置时,这很容易做到:
<job-repository id="jobRepository" table-prefix="GFA.BATCH_" />
Run Code Online (Sandbox Code Playgroud)
但是,当我使用Java Config时,这变得更加棘手。我发现的最佳解决方案是拥有我的Java Config类extend DefaultBatchConfigurer并重写该createJobRepository()方法:
@Configuration
@EnableBatchProcessing
public class BatchConfiguration extends DefaultBatchConfigurer{
@Autowired
private DataSource dataSource;
@Autowired
private PlatformTransactionManager transactionManager;
@Override
protected JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setTablePrefix("GFA.BATCH_");
factory.afterPropertiesSet();
return factory.getObject();
}
...
}
Run Code Online (Sandbox Code Playgroud)
与XML解决方案相比,这几乎就是代码!而且也不太合逻辑-我的第一个猜测是提供一种@Bean方法,如下所示:
@Bean
public JobRepository jobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setTablePrefix("GFA.BATCH_");
factory.afterPropertiesSet();
return factory.getObject();
}
Run Code Online (Sandbox Code Playgroud)
但这行不通。
我的问题是:我的解决方案是最优的还是有更好的解决方案?我宁愿定义一个Bean,而不必重写不是很直观的某些类的方法。显然,如果我们可以缩短代码使其在某种程度上接近单行代码,那会更好。 XML配置。
我无法在 ServletContextListener 中获取 WebApplicationContext。我寻找解决方案,但没有一个适合我。如果有人可以提供帮助,我将不胜感激。提前致谢。
以下是代码片段 - 我的 AppConfig 类:
package in.andonsystem.config;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"in.andonsystem"})
public class AppConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public MessageSource messageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
} …Run Code Online (Sandbox Code Playgroud) 默认情况下,sec:authorize-url标记不能与Spring启动安全性一起使用:
git clone https://github.com/spring-projects/spring-boot
Run Code Online (Sandbox Code Playgroud)
添加依赖项
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity3</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
调整样本中的控制器:
@RequestMapping("/")
public String home(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}
@RequestMapping("/admin/foo")
public String home2(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}
Run Code Online (Sandbox Code Playgroud)
添加与应用程序安全性匹配的URL:
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
...
Run Code Online (Sandbox Code Playgroud)
在home.html中添加testcode
<div sec:authorize="hasRole('ROLE_ADMIN')">
has role admin
</div>
<div sec:authorize-url="/admin/foo">
can see /admin
</div>
Run Code Online (Sandbox Code Playgroud)
当我启动应用程序并登录时,无论我是否可以实际访问该URL,我都会看到"可以看到/管理员"部分.角色评估本身按预期工作,url权限本身也是如此(当我尝试使用ROLE_USER访问它时,我得到403).
如果我向web安全配置添加一个dummy privilegeEvaluator,它只是为每个请求返回false,则div将正确消失.
我在这里错过了什么吗?这是预期的行为,我需要定义什么才能使authorize-url以与使用xml配置安全性时相同的方式工作?
此问题与SpringBootWebSecurityConfiguration中的基本身份验证及其自动配置相关联:
在 …
spring spring-security thymeleaf spring-boot spring-java-config
在使用Spring的Java配置时,您必须看到类似WebMvcConfigurerAdapter 和HandlerInterceptorAdapter的类,这些类实现了单个接口,并且它们遵循应该为真实适配器保留的*Adpater约定(此特定类不会将调用从一个接口转换为不同的界面).
有没有人知道我的理解是否有任何问题/他们使用错误的惯例?
spring design-patterns spring-mvc naming-conventions spring-java-config
spring ×8
spring-mvc ×5
java ×4
cas ×1
hibernate ×1
maven ×1
multi-module ×1
security ×1
spring-batch ×1
spring-boot ×1
thymeleaf ×1