3

看起来好像没有添加一些过滤器。我将 Spring security 3.2.0.RELEASE 与 java-config 一起使用。GitHub SecurityConfig.java上发布的完整项目在 这里:SecurityConfig.java

我尝试在以下位置设置过滤器:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/app/**").hasRole("ADMIN")
                .and()
                .formLogin()
                .loginPage("/")
                .defaultSuccessUrl("/app/")
                .failureUrl("/?error=1")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/?logout");
    }

在 csrf().disable() 之后 - 但问题没有解决......请帮我解决这个问题,因为我可以将 /j_spring_security_check 与我自己的 CustomUserDetailsS​​ervice 一起使用!

4

1 回答 1

4

我没有使用 Spring Security Java Config 的经验,但是我检查了您的代码和 API,似乎设置登录处理 URL 可以让您登录:

AbstractAuthenticationFilterConfigurer.loginProcessingUrl("/j_spring_security_check")

所以你的代码应该是:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/app/**").hasRole("ADMIN")
            .and()
            .formLogin()
            .loginProcessingUrl("/j_spring_security_check")
            .loginPage("/")
            .defaultSuccessUrl("/app/")
            .failureUrl("/?error=1")
            .permitAll()
            .and()
            .logout()
            .logoutSuccessUrl("/?logout");
}

我希望这是默认设置的。

此外,为了使用 MyCustomUserDetailsS​​ervice,而不是像现在这样自动装配它(由 Spring 创建的代理),我将手动配置它:

public class MyCustomUserDetailsService implements UserDetailsService {

    private UserDAO userDAO;

    public MyCustomUserDetailsService(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    // ...    
}

注意,没有@Service/@Component 注释和通过Ctor 注入的DAO。在安全配置中:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserDAO userDAO;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .and()
                .userDetailsService(new MyCustomUserDetailsService(userDAO));
    }
    // ...
}

现在我确定 UserDetailService 已正确配置。并且肯定会在登录应用程序时使用它。

我还注意到没有使用用户名和密码。这是因为在 login.jsp 中您使用 j_username 和 j_password 而用户名参数应该是用户名和密码参数应该是密码。

<input type="text" id="username" class="span4" name="username" placeholder="Username" />
<input type="password" id="password" class="span4" name="password" placeholder="Password" />

查看 FormLoginConfigurer 类。

于 2014-01-24T22:06:48.350 回答