【问题标题】:Unauthorized access with spring security未经授权的访问与弹簧安全
【发布时间】:2016-01-02 12:44:32
【问题描述】:

我尝试为休息应用程序添加安全性。

我遵循了这个教程: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,它在 index.html 中加载(通过 jquery)一些其他 html 文件。

我尝试使用 curl 访问服务

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

我得到一个

HTTP/1.1 401 Unauthorized

所有带有休息的网址都是安全的,但我提供的用户名和密码应该是单词。

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

有些东西链接不正确。

【问题讨论】:

    标签: spring spring-security spring-boot spring-restcontroller spring-rest


    【解决方案1】:

    您需要登录才能访问受限资源。 Spring security 为执行身份验证提供了默认入口点。这就是您给定链接的这一部分的作用:

    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 /login url 和你的 usernamepassword 参数。这就是 curl 的处理方式:

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

    这样做是使用您的凭据登录并将给定的 cookie 存储在 cookies.txt 文件中。然后,您只需在执行的每个请求中附加该 cookie 即可在您的服务器中获得权限:

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

    另请参阅:

    【讨论】:

    • 谢谢你的工作,只需要看看有没有办法保护我的html文件。
    猜你喜欢
    • 2013-07-16
    • 2017-07-21
    • 2021-08-24
    • 2015-04-19
    • 1970-01-01
    • 2011-05-16
    • 2015-03-05
    • 1970-01-01
    • 2020-05-27
    相关资源
    最近更新 更多