【问题标题】:Spring Security + jQuery: Uncaught SyntaxError: Unexpected token <Spring Security + jQuery: Uncaught SyntaxError: Unexpected token <
【发布时间】:2018-07-21 19:23:04
【问题描述】:

我在将 Spring Security 身份验证与 jQuery 耦合时遇到了麻烦。实际上脚本甚至没有运行 - 当我点击时没有任何反应 在浏览器的控制台中,我在 login.js:1 中找到了消息:Uncaught SyntaxError: Unexpected token &lt;

我已经阅读了之前回答的一些问题,并意识到这是关于返回错误 ContentType 的问题,但我不知道如何解决它。我认为它可能也与 Spring Security 资源保护有关。我添加了下面发布的配置行以将其关闭,这至少使 css 工作。

奇怪的是,当我在控制台中转到 Sources 时,然后单击 login.js 出现 html 代码而不是 js 代码。

恳请大家帮忙整理一下:)

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**").anyRequest();
}

$(document).ready(function(){
    $("#login").click(function(){
        var email = $("#username").val();
        var password = $("#password").val();
// Checking for blank fields.
        if( email =='' || password ==''){
            $('input[type="text"],input[type="password"]').css("border","2px solid red");
            $('input[type="text"],input[type="password"]').css("box-shadow","0 0 3px red");
            alert("Please fill all fields...!!!!!!");
        }else {
            $.post("login",{username: email, password: password},
                function(data) {
                    if(data=='Invalid Email.......') {
                        $('input[type="text"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
                        $('input[type="password"]').css({"border":"2px solid #00F5FF","box-shadow":"0 0 5px #00F5FF"});
                        alert(data);
                    }else if(data=='Email or Password is wrong...!!!!'){
                        $('input[type="text"],input[type="password"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
                        alert(data);
                    } else if(data=='Successfully Logged in...'){
                        $("form")[0].reset();
                        $('input[type="text"],input[type="password"]').css({"border":"2px solid #00F5FF","box-shadow":"0 0 5px #00F5FF"});
                        alert(data);
                    } else{
                        alert(data);
                    }
                });
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
    <title>Login page</title>
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <link rel="stylesheet" type="text/css" href="style.css"></link>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="login.js" type="text/javascript"></script>
</head>
<body>
<h1>Login page</h1>
<form>
    <label for="username">Username</label>:
    <input type="text" id="username" name="username" autofocus="autofocus"/> <br/>
    <label for="password">Password</label>:
    <input type="password" id="password" name="password"/> <br/>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="button" id="login" value="Log in"/>
</form>
</body>
</html>
@Controller
public class Login {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
    return "login";
}

@RequestMapping(value = "/homepage", method = RequestMethod.GET)
public String homepage() {
    return "homepage";
}

}

@EnableWebSecurity
@Configuration
public class SecConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider
            = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(encoder());
    return authProvider;
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/login*").anonymous()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login.html")
            .defaultSuccessUrl("/homepage.html")
            .failureUrl("/login.html?error=true")
            .and()
            .logout().logoutSuccessUrl("/login.html");
}
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**").anyRequest();
}
}

编辑: 当我删除调用 anyRequest(); web.ignoring().antMatchers("/resources/**").anyRequest() 中的方法;还有一个错误:

Refused to execute script from 'http://localhost:8080/login.js' because its MIME type ('text/html') is 
not executable, and strict MIME type checking is enabled. 

【问题讨论】:

  • 你应该提供你所有的spring-security 配置和任何相关的日志消息
  • 我在问题中添加了安全配置 sn-p。

标签: java jquery spring spring-mvc spring-security


【解决方案1】:

我想问题可能是由于csrf。实际上有一个 sn-p,但我认为在您的 jquery post 中您没有发送它。

Unexpected token &lt; 消息可能是由于 CSRFFilter 发送 html 编码的 http 401403 响应。

您可以尝试在安全配置中禁用 csrf 以检查它是否工作,如果它最终以这种方式工作,那么您可以进行适当的更改以在不破坏 login @987654330 的情况下将其打开@

【讨论】:

  • 我将 csrf().disable() 添加到我的 HttpSecurity 配置中,但仍然没有运气。所有响应都有代码 200。这很奇怪,因为当我在开发工具中单击 login.js 脚本时出现 html 代码。我不明白 - 为什么?
【解决方案2】:

我们必须在所有的post请求中传递header和token,

             var token = $("meta[name='_csrf']").attr("content"); 

               var header = 
               $("meta[name='_csrf_header']").attr("content");

          xhttp.setRequestHeader(header, token);
          xhttp.send();

【讨论】:

  • 我禁用了反csrf保护,但它仍然不起作用。我认为编码或其他东西有问题。在开发工具中,当我单击 login.js 脚本时会出现 html 代码。为什么?
猜你喜欢
  • 2011-04-02
  • 1970-01-01
  • 2016-04-06
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多