当前位置: 首页 > 知识库问答 >
问题:

无法登录Spring Security

扈沛
2023-03-14

我在实现基于注释的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());
    }


}

当我启动我的服务器时,它会进入StatesLoginFilter构造函数。但是,当我访问我的页面时,它直接显示我访问被拒绝,而没有进入我的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个答案

冯嘉珍
2023-03-14

尝试禁用CSFR:

http
    .csrf().disable();

或者实施它。

 类似资料:
  • 我尝试使用这个简单的代码登录,但在我点击登录按钮后,else选项“无效用户名或密码!”总是出现,即使用户名和密码是匹配的 控制器:

  • 每当我试图打开 致命错误:未捕获错误:调用C:\xampp\htdocs\wordpress\wp includes\wp db中未定义的函数mysql\u connect()。php:1668堆栈跟踪:#0 C:\xampp\htdocs\wordpress\wp includes\wp db。php(632):wpdb- 致命错误:未捕获错误:调用C:\xampp\htdocs\wordpre

  • 我正在将Symfony 3.1与FOSUserBundle一起使用。 我读了Symfony中的文档和集成的FOS,在这里好吧,注册似乎运行良好,并将数据持久化到数据库,但是,如果我尝试登录,我会再次被重定向到作为匿名用户的登录页面。 我检查了Symfony探查器,我可以看到当它被称为path/login\u check(在探查器中)时,用户结果是经过身份验证的,但是在/login\u check阶

  • 所以我正在尝试在 Spring 启动和安全的帮助下创建简单的登录页面。所以我目前拥有的是自定义登录页面和一个用户和角色的内存身份验证。问题是,当我输入正确的用户/密码时,spirng没有将其认证为有效数据,并再次将我重定向到登录页面,但这次是: 在客户端,我使用胸腔叶。 表单片段: 配置类: 控制器简单 知道我做错了什么吗?

  • 我正面临一个奇怪的admob登录问题,无法找到任何解释这个确切的问题在网上。问题来了:--我有一个admob账户--我在这个账户上安装了一个应用程序链接--应用商店上发布的应用程序完美地显示了广告--但在此之后的3、4天,我就无法登录我的admob账户了。与此同时,该应用程序已经停止显示这些广告。-每次我尝试登录时,admob网页都告诉我“您当前以charlesdurandjp@gmail.com

  • 问题内容: 我使用PuTTY SSH会话从Windows 10笔记本电脑登录到服务器。 我的本地Windows笔记本电脑上没有Docker,因此所有工作都在远程服务器上完成。 我可以使用终端会话在远程服务器上执行所有Docker命令。 但是,当我尝试将映像保存到Docker集线器时,尝试登录时,请使用: 我收到以下错误消息: 在远程服务器上创建映像时,没有收到任何错误消息。 我也没有在远程服务器上