当前位置: 首页 > 面试题库 >

Spring Security 4自定义登录j_spring_security_check返回http 302

唐俊英
2023-03-14
问题内容

我在这里问了有关最新的Spring框架和基于代码的配置的问题

initializer

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MvcConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

MVC config

    @EnableWebMvc
    @ComponentScan({ "com.appname.controller" })
    public class MvcConfig extends WebMvcConfigurerAdapter {
        @Bean
        public InternalResourceViewResolver viewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/jsp/");
            resolver.setSuffix(".jsp");
            return resolver;
        }

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

security config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private CustomUserDetailsService customUserDetailsService;

public SecurityConfig() {
    customUserDetailsService = new CustomUserDetailsService();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password")
            .roles("USER");
    auth.userDetailsService(customUserDetailsService);
}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/res/**").permitAll()
            .and().authorizeRequests()
            .anyRequest().hasRole("USER")
            .and().formLogin().loginPage("/account/signin").permitAll()
            .and().logout().permitAll();
    }
}

security initializer

public class SecurityInitializer extends
        AbstractSecurityWebApplicationInitializer {

}

custom login

public class CustomUserDetailsService implements UserDetailsService {

    private AccountRepository accountRepository;

    public CustomUserDetailsService() {
        this.accountRepository = new AccountRepository();
    }

    @Override
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException {

        Account account = accountRepository.getAccountByEmail(email);

        if (account == null) {
            throw new UsernameNotFoundException("Invalid email/password.");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("USER"));

        return new User(account.getEmail(), account.getPassword(), authorities);
    }
}

但是,现在我有关于自定义登录的新问题。

发布到j_spring_security_check时,我会收到http 302。

我正在请求/,但登录后仍保留在登录页面上。

因为我使用的是Spring Security 4.x版本,并且纯粹基于代码的配置,所以在Internet上找不到更多参考。任何人都可以帮助找出原因。

EDIT

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'securityConfig': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: 
private org.springframework.security.core.userdetails.UserDetailsService sg.mathschool.infra.SecurityConfig.userDetailsService; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}

I changed CustomUserDetailsService

@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    private AccountRepository accountRepository;

    public CustomUserDetailsService() {
        this.accountRepository = new AccountRepository();
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException {

        Account account = accountRepository.getAccountByEmail(email);

        if (account == null) {
            throw new UsernameNotFoundException("Invalid email/password.");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("USER"));

        return new User(account.getEmail(), account.getPassword(), authorities);
    }
}

和 security config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password")
                .roles("USER");
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/res/**").permitAll()
                .antMatchers("/account/**").permitAll().anyRequest()
                .hasRole("USER").and().formLogin().loginPage("/account/signin")
                .failureUrl("/account/signin?error").usernameParameter("email")
                .passwordParameter("password").and().logout()
                .logoutSuccessUrl("/account/signin?logout").and().csrf();

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
}

问题答案:

在Spring Security 4.x中,登录URL已更改为,login而不是 j_spring_security_check,请参阅从Spring Security 3.x迁移至4.x(XML配置)。

<form name='f'action="login" method='POST'>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <table>
        <tbody>
            <tr>
                <td>User Name</td>
                <td><input type="text" name="username" size="30" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password" size="30" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="login" /></td>
            </tr>
        </tbody>
    </table>
</form>


 类似资料:
  • 有人能告诉我一些资源吗?这些资源可以指导我如何实现一个定制的Spring Security身份验证,首先在ldap服务器上测试找到的用户的凭据,如果该用户的ldap用户名字段存在,如果无法进行身份验证(可能是因为ldap用户名不存在,或者给定的密码没有对服务器上的用户名进行身份验证),则会尝试根据本地数据库中散列的用户本地密码进行身份验证。 非常感谢。

  • 这是一个概念问题。 我这样问的原因是,有些其他RESTful服务使用401处理错误的凭据,即使您只是询问凭据是否有效。然而,我对401响应的理解是,它们代表了一个没有有效凭据的资源。但登录资源应该对任何人都可以访问,因为登录资源的全部目的是告诉您凭据是否有效。 换句话说,在我看来,像这样的请求: 如果提供了错误的凭据,则应返回401。而是这样的请求: 关于这件事,我想听听一些合理的意见。处理这件事

  • 改变json输出策略 默认使用阿里的fastjson进行json输出 JSON.toJSONString(obj) 如果要更换输出策略,操作方式如下: @Override protected void initApiConfig(ApiConfig apiConfig) { ... // 自定义json格式输出,将null字符串变成"" apiConfig.setJson

  • 网关默认对业务结果进行合并,然后返回统一的格式。 针对alipay.story.find接口,微服务端返回结果如下: { "name": "白雪公主", "id": 1, "gmtCreate": 1554193987378 } 网关合并后,最终结果如下 { "alipay_story_find_response": { "msg": "Succe

  • 接口说明 登录并返回token 如需调用,请访问 开发者文档 来查看详细的接口使用说明 该接口仅开放给已获取SDK的开发者 如开启https功能,请求地址的协议应改为https,如:https://www.example.com/wish3dearth/api/access/v1.0.0/getLicenseInfo API地址 POST /authcenter/api/login/v1.0.0/

  • 请参考一些wordpress post登录插件。我有3页的网站主页,关于正常工作和工作安全,我想显示工作安全页面,如果用户登录有电子邮件/只是虚拟id,我可以生成。找不到此登录模块的插件。带有自定义页面的自定义菜单 使用这个脚本,我可以创建菜单,但不能重定向单独的页面 函数my_wp_nav_menu_args($args=''){ 如果(用户是否已登录){ }否则{ } } 添加过滤器(“wp\