0

我尝试将安全性添加到其他应用程序。未授权访问弹簧安全

我跟着这个教程:http://www.codesandnotes.be/2014/10/31/restful-authentication-using-spring-security-on-spring-boot-and-jquery-as-a-web-client/

我配置我的课谁扩展WebSecurityConfigurerAdapter。

http.authorizeRequests().antMatchers("/rest/**").authenticated(); 
http.csrf().disable(); 
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); 
http.formLogin().successHandler(authenticationSuccessHandler); 
http.formLogin().failureHandler(authenticationFailureHandler); 

我有一个login.html,index.html谁加载(通过jQuery)一些其他HTML文件在index.html。

我试着用卷曲

curl -i -X POST -d username=test -d password=test http://localhost:8080/rest/cities 

访问服务,我收到了

HTTP/1.1 401 Unauthorized 

与其余所有URL被固定,但我提供的用户名和密码应字。

当我调试时,我看到,然后我的类实现UserDetailsS​​ervice谁拥有方法loadUserByUsername永远不会被调用。

有些人不正确地做链接。

回答

1

您需要先登录才能访问受限资源。 Spring安全提供了一个默认的入口点来执行你的认证。这就是你给的链接,这部分的作用:

jQuery(document).ready(function ($) { 
    $('#loginform').submit(function (event) { 
     event.preventDefault(); 
     var data = 'username=' + $('#username').val() + '&password=' + $('#password').val(); 
     $.ajax({ 
      data: data, 
      timeout: 1000, 
      type: 'POST', 
      url: '/login' 

     }).done(function(data, textStatus, jqXHR) { 
      var preLoginInfo = JSON.parse($.cookie('dashboard.pre.login.request')); 
      window.location = preLoginInfo.url; 

     }).fail(function(jqXHR, textStatus, errorThrown) { 
      alert('Booh! Wrong credentials, try again!'); 
     }); 
    }); 
}); 

所以,你需要POST/登录网址与你的用户名密码参数。这就是它是如何与卷曲做到:

curl -i -X POST -d username=user -d password=userPass -c /opt/cookies.txt 
http://localhost:8080/rest/login 

这样做是与您的凭据登录并存储在cookie.txt的文件中给出的cookie。然后,你只需要附上该cookie在每一个请求进行以获得许可,您的服务器:

curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txt 
http://localhost:8080/rest/cities 

参见:

+0

感谢工作,只需要看看有没有办法保护我的html文件。 –