无法登录 Spring Security

Posted

技术标签:

【中文标题】无法登录 Spring Security【英文标题】:Unable to login in Spring Security 【发布时间】:2016-07-09 08:23:23 【问题描述】:

我在实现基于注解的 Spring Security 时遇到了一个问题。

当我从我的 Angular UI 发布数据时,它会触发 Spring Security,但它根本不会进入登录尝试。我不知道我哪里做错了。

我的无状态登录过滤器是:

class StatelessLoginFilter extends AbstractAuthenticationProcessingFilter 

    private final TokenAuthenticationService tokenAuthenticationService;
    private final CustomJDBCDaoImpl userDetailsService;

    protected StatelessLoginFilter(String urlMapping, TokenAuthenticationService tokenAuthenticationService,
            CustomJDBCDaoImpl userDetailsService, AuthenticationManager authManager) 
        super(new AntPathRequestMatcher(urlMapping));
        this.userDetailsService = userDetailsService;
        this.tokenAuthenticationService = tokenAuthenticationService;
        setAuthenticationManager(authManager);
    

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException 

                final UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken(
                request.getParameter("username").toString(), request.getParameter("password").toString());
        return getAuthenticationManager().authenticate(loginToken);
    

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            FilterChain chain, Authentication authentication) throws IOException, ServletException 

        // Lookup the complete User object from the database and create an Authentication for it
        final UserDetails authenticatedUser = userDetailsService.loadUserByUsername(authentication.getName());
        final UserAuthentication userAuthentication = new UserAuthentication(authenticatedUser);

        // Add the custom token as HTTP header to the response
        tokenAuthenticationService.addAuthentication(response, userAuthentication);

        // Add the authentication to the Security context
        SecurityContextHolder.getContext().setAuthentication(userAuthentication);
    

而我的spring security配置文件是:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
@Order(1)
public class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter 


    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    public StatelessAuthenticationSecurityConfig() 
        super(true);
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
                .exceptionHandling().and()
                .anonymous().and()
                .servletApi().and()
                .headers().cacheControl().and()
                .authorizeRequests()

                //allow anonymous resource requests
//              .antMatchers("/").permitAll()
                .antMatchers("/favicon.ico").permitAll()
                .antMatchers("/resources/**").permitAll()

                //allow anonymous POSTs to login
                .antMatchers(HttpMethod.POST, "/api/login").permitAll()

                //allow anonymous GETs to API
                .antMatchers(HttpMethod.GET, "/api/**").permitAll()

                //defined Admin only API area
                .antMatchers("/api/admin/**").hasRole("ADMIN")

                //all other request need to be authenticated
                .anyRequest().hasRole("USER").and()             

                // custom JSON based authentication by POST of "username":"<name>","password":"<password>" which sets the token header upon authentication
                .addFilterBefore(new StatelessLoginFilter("/api/login", tokenAuthenticationService, new CustomJDBCDaoImpl(), authenticationManager()), UsernamePasswordAuthenticationFilter.class)

                // custom Token based authentication based on the header previously given to the client
                .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
    

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(new CustomJDBCDaoImpl()).passwordEncoder(new BCryptPasswordEncoder());
    



当我启动我的服务器时,它会进入 StatlessLoginFilter 构造函数。但是,当我访问我的页面时,它直接显示我访问被拒绝,而无需进入我的 statelessloginfilter 类的尝试登录方法。

我的 AngularJS 发布请求如下所示:

$http.post('/api/login',  username: $scope.user.email, password: $scope.user.password ).success(function (result, status, headers) 
            $scope.authenticated = true;

编辑#1:

添加 http.csrf().disable() 后,我开始尝试身份验证。但是,现在请求参数为空。

Info:   2016-03-23 00:59:59 DEBUG FilterChainProxy:337 - /api/login at position 1 of 7 in additional filter chain; firing Filter: 'HeaderWriterFilter'
Info:   2016-03-23 00:59:59 DEBUG FilterChainProxy:337 - /api/login at position 2 of 7 in additional filter chain; firing Filter: 'StatelessLoginFilter'
Info:   2016-03-23 00:59:59 DEBUG AntPathRequestMatcher:145 - Checking match of request : '/api/login'; against '/api/login'
Info:   2016-03-23 00:59:59 DEBUG StatelessLoginFilter:205 - Request is to process authentication
Warning:   StandardWrapperValve[com.security.AppConfig]: Servlet.service() for servlet com.security.AppConfig threw exception
java.lang.NullPointerException
....

【问题讨论】:

【参考方案1】:

尝试禁用CSFR:

http
    .csrf().disable();

或者implementing它。

【讨论】:

以上是关于无法登录 Spring Security的主要内容,如果未能解决你的问题,请参考以下文章

Grails + Spring Security:无法登录

我无法使用 Spring Security 登录

自定义登录表单无法使用 Spring Security

由于重定向循环,Grails Spring Security 无法显示登录页面

spring-security 登录 无法进入UserDetailsService类

Spring security“forward:”指令无法转发到登录表单