标签: spring-java-config

Spring Security:无法使用java config配置方法安全性

我正在努力用java配置的spring安全性来配置方法安全性.我的配置没有任何问题,直到我在任何控制器中使用@Secured注释.

Spring Security Config:(java config)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers("/webjars/**","/css/**", "/less/**","/img/**","/js/**");
    }

    @Autowired
    public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
        ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(256);
        auth
          .jdbcAuthentication()
              .dataSource(dataSource)
              .usersByUsernameQuery(getUserQuery())
              .authoritiesByUsernameQuery(getAuthoritiesQuery())
              .passwordEncoder(shaPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
            .anyRequest().hasAuthority("BASIC_PERMISSION")
            .and()
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/success-login", true)
            .failureUrl("/error-login")
            .loginProcessingUrl("/process-login")
            .usernameParameter("security_username")
            .passwordParameter("security_password")
            .permitAll() 
            .and()
        .logout()
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .permitAll()
            .and()
        .rememberMe()
            .key("04E87501B3F04DB297ADB74FA8BD48CA") …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security spring-java-config

3
推荐指数
1
解决办法
4322
查看次数

使用Java配置的Spring Security:如何从自定义提供程序处理BadCredentialsException

我需要使用url中的令牌ID(或者可能在请求标头中)对一些休息服务进行身份验证 - 但这对于现在来说并不重要.我正在尝试使用java配置来设置它作为这篇文章的指南.我的问题是我不知道如何处理从提供程序验证失败时引发的"BadCredentialsException".这是我的安全配置:

public static class SecurityConfigForRS extends
        WebSecurityConfigurerAdapter {

    @Autowired
    TokenAuthenticationProvider tokenAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.authenticationProvider(tokenAuthenticationProvider);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.regexMatcher("^/rest.*")
                .addFilterBefore(
                        new TokenAuthenticationFilter(
                                authenticationManagerBean()),
                        AbstractPreAuthenticatedProcessingFilter.class)
                .and().csrf().disable();

    }
}
Run Code Online (Sandbox Code Playgroud)

现在我跳过其他实现 - 如果它有帮助我将在以后发布它们.

当令牌丢失或无效时,TokenAuthernticationProvider抛出a BadCredentialsException.我需要抓住这个并发回一个401-Unauthorized.是否有可能做到这一点?

spring-security spring-java-config

3
推荐指数
1
解决办法
9218
查看次数

Spring JavaConfig配置异常:需要ServletContext来配置默认的servlet处理

我试图用纯Spring 4.1.0 JavaConfig设置替换我的web.xml.根据我阅读的示例和API文档,以下"应该"工作:

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        // Create the root appcontext (replaces the web.xml context-param & ContextLoaderListener)
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootConfig.class);
        // since we registered RootConfig instead of passing it to the constructor
        rootContext.refresh(); 
    ...
    ...
}

}
Run Code Online (Sandbox Code Playgroud)

使用RootConfig.java:

@Configuration
@ComponentScan(basePackages="com.ia", excludeFilters=@ComponentScan.Filter(type=FilterType.ANNOTATION, value=Controller.class))
@EnableSpringConfigured
public class RootConfig{
}
Run Code Online (Sandbox Code Playgroud)

但是,这样做时,我收到以下错误消息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Instantiation of bean failed; nested …
Run Code Online (Sandbox Code Playgroud)

java configuration spring tomcat spring-java-config

3
推荐指数
1
解决办法
6896
查看次数

多个ThreadPoolTask​​执行Spring Java配置

我的应用程序中需要多个任务执行器,但我没有看到如何使用Java Config.XML版本很简单,但我必须遗漏Java Config

我需要两个具有不同队列和线程池大小的不同执行程序,如何使用Java Config完成此操作?

这是我的AsyncConfig类

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@EnableScheduling
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Autowired
    Environment environment;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(environment.getRequiredProperty("aysnc.executor.poolSize", Integer.class));
        executor.setMaxPoolSize(environment.getRequiredProperty("aysnc.executor.maxPoolSize", Integer.class));
        executor.setQueueCapacity(environment.getRequiredProperty("aysnc.executor.queueCapacity", Integer.class));
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-java-config

3
推荐指数
1
解决办法
6597
查看次数

如何使用Spring Boot动态创建imap接收器适配器?

我如何创建直接通道,imap通道适配器并传递用户帐户信息,以便程序开始查找新邮件。

我已经使用xml config实现了邮件接收器。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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.xsd
    http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
    http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
   xmlns:int="http://www.springframework.org/schema/integration"
   xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
   xmlns:util="http://www.springframework.org/schema/util">

<int:channel id="emails"/>

<util:properties id="javaMailProperties">
    <prop key="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
    <prop key="mail.imap.socketFactory.fallback">false</prop>
    <prop key="mail.store.protocol">imaps</prop>
    <prop key="mail.debug">true</prop>
</util:properties>

<int-mail:imap-idle-channel-adapter id="mailAdapter"
                              store-uri="imaps://login:pass@imap-server:993/INBOX"
                              java-mail-properties="javaMailProperties"
                              channel="emails"
                              should-delete-messages="false"
                              should-mark-messages-as-read="true">
</int-mail:imap-idle-channel-adapter>
Run Code Online (Sandbox Code Playgroud)

以下是使用xml文件的Java文件。

public class EmailIntegrationTesting {

private static Logger logger = LoggerFactory.getLogger(EmailIntegrationTesting.class);

public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext("gmail-imap.xml");

    DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
    inputChannel.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException …
Run Code Online (Sandbox Code Playgroud)

java spring spring-integration spring-boot spring-java-config

3
推荐指数
1
解决办法
3111
查看次数

StackOverflowError试图在Spring WebSecurityConfigurerAdapter中公开AuthenticationManager

我试图通过扩展WebSecurityConfigurerAdapter来创建一个Spring Security配置,基本上是这样的:

@EnableWebSecurity
@Configuration
public class StackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(myUsernamePasswordProvider());
        auth.authenticationProvider(mySecurityTokenProvider());

        super.configure(auth);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public MyPreAuthenticatedProcessingFilter myAuthenticationFilter() throws Exception {
        MyPreAuthenticatedProcessingFilter myAuthenticationFilter = new MyPreAuthenticatedProcessingFilter();
        myAuthenticationFilter.setAuthenticationManager(authenticationManager());

        return myAuthenticationFilter;
    }

}
Run Code Online (Sandbox Code Playgroud)

我看到了这个:

SEVERE: Servlet.service() for servlet [servlet] in context with path [/MyApp] threw exception [Filter execution threw an exception] with root cause
[INFO] [talledLocalContainer] java.lang.StackOverflowError
[INFO] [talledLocalContainer]   at org.springframework.security.authentication.AnonymousAuthenticationProvider.supports(AnonymousAuthenticationProvider.java:79)
[INFO] [talledLocalContainer] …
Run Code Online (Sandbox Code Playgroud)

java spring filter spring-security spring-java-config

3
推荐指数
1
解决办法
2033
查看次数

InvalidDataAccessApiUsageException:执行更新/删除查询Spring XML to Java config

我正在尝试将spring xml配置转换为java配置.这通过XML配置完美地工作.但是,如果我使用java config initializer,它会抛出以下异常.当它尝试运行JQL时会发生这种情况.应用程序正常启动(初始化所有JPA映射).

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslat
Run Code Online (Sandbox Code Playgroud)

以下是我的持久化初始化类.一点点阅读建议我这与交易没有正确启动有关.我已经将调试点放到这些方法中,但是在服务器启动期间或之后的任何时间都不会执行transactionManager方法.我不确定我做错了什么:(.当通过persistence.xml初始化持久性时,基于相同代码的工作非常完美.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "au.mypkg")
public class DatabaseConfig  {


    @Bean(name = "dataSource")
    @Primary
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:jboss/datasources/mydb");
    }

    @PersistenceContext(unitName = "persistenceUnit")
    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
    ..........

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { …
Run Code Online (Sandbox Code Playgroud)

spring hibernate spring-transactions spring-data-jpa spring-java-config

3
推荐指数
2
解决办法
8591
查看次数

@EnableJpaRepositories寻找哪个包?

我正在学习如何构建JSF和Spring集成的webapp.我正在使用java配置进行配置.问题是@EnableJpaRepositories,我应该在这个注释中添加哪个包?包中包含实体类?还是配置类?要么?我可以将我的root包放入其中并让它自己搜索吗?

spring spring-java-config

3
推荐指数
1
解决办法
3877
查看次数

Weblogic jndi使用java配置发生NameNotFoundException

我一直在寻找这个问题,我无法使用java配置找到jndi数据库.在此之前我使用xml及其工作完美但在java配置中它会导致问题;

Xml代码:

     <!-- Jndi database connection -->
     <jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}"
     resource-ref="true" />

     <beans:bean id="jdbcTemplate"
     class="org.springframework.jdbc.core.JdbcTemplate" >
     <beans:property name="dataSource" ref="dbDataSource"></beans:property>
     </beans:bean>
Run Code Online (Sandbox Code Playgroud)

Java配置现在:

@Bean(name = "dbDataSource")
public DataSource dataSource(@Value("${db.jndi}") String jndiName) 
{
    JndiDataSourceLookup lookup = new JndiDataSourceLookup();
    return lookup.getDataSource(jndiName);
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) { 
    return new JdbcTemplate(ds);
}
Run Code Online (Sandbox Code Playgroud)

属性文件:

db.jndi=jndi/myData
Run Code Online (Sandbox Code Playgroud)

weblogic中的JNDI名称:

jndi/myData
Run Code Online (Sandbox Code Playgroud)

更改为java配置后,有时系统可以读取数据库但很少发生,直到我清理并重新启动计算机然后它才能找到数据库,但通常它总是触发:

javax.naming.NameNotFoundException: Unable to resolve 'jndi.myData'. Resolved 'jndi'; remaining name 'myData'

为什么应用程序无法正确找到数据库?谢谢!!!

spring weblogic spring-java-config

2
推荐指数
1
解决办法
2813
查看次数

Spring Java配置相同的Bean引用

通过问题在Spring的Java配置中自动装配bean我得到了一个问题.

@Configuration
public class Config {

   @Bean
   public RandomBean randomBean(){
       return new RandomBean();
   }

   @Bean
   public AnotherBean anotherBean(){
       return new AnotherBean(randomBean()); // this line
   }

}
Run Code Online (Sandbox Code Playgroud)

Spring如何保证该方法randomBean()将返回与注入的方法相同的引用AnotherBean

它是通过代理实现的吗?

另一方面,通过提供依赖项作为方法参数来实现它是显而易见的:

@Configuration
public class Config {

   @Bean
   public RandomBean randomBean(){
       return new RandomBean();
   }

   @Bean
   public AnotherBean anotherBean(RandomBean randomBean){
       return new AnotherBean(randomBean);
   }

}
Run Code Online (Sandbox Code Playgroud)

编辑:最后,我发现了有关基于Java的配置如何内部工作的更多信息中描述的此行为主题.

java spring spring-java-config

2
推荐指数
1
解决办法
2229
查看次数