Securing REST endpoint using spring security

雨燕双飞 提交于 2019-12-05 02:52:14

The example you have followed is implementing a form-based authentication. In order to change it to http auth (which is more suitable for REST services) you need to look for the following form-login tag in your security.xml:

<form-login 
        login-page="/login" 
        default-target-url="/welcome" 
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password" />

And just change it to an empty http-basic tag:

<http-basic />

If you did not change anything else, then it supposed to work perfectly. You can also test your setup from your browser, by trying to access your page. If you configured everything properly you will get a popup this time, not a form. That will be HTTP-basic authentication welcoming you.

Since likely you are using the Java-based configuration, the equivalent of this change would be to replace:

  http.authorizeRequests()
    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
    .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
    .and().formLogin();

with:

  http.authorizeRequests()
    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
    .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
    .and().httpBasic();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!