有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在Spring Security中登录

我在实现基于注释的Spring安全性时遇到了一个问题

当我从我的angular UI发布数据时,它会点击Spring安全性,但根本不会进入登录尝试。我不知道我哪里做错了

我的无状态登录筛选器是:

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安全配置文件是:

@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构造函数。但是,当我访问我的页面时,它直接显示拒绝访问,而不进入我的无状态LoginFilter类的attemptLogin方法

我的AngularJS post请求如下所示:

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

编辑#1:

在添加http之后。csrf()。禁用()我必须尝试身份验证。但是,现在请求参数为null

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) 个答案

  1. # 1 楼答案

    尝试禁用CSFR

    http
        .csrf().disable();
    

    或者implementing