I am trying to provide security to the REST endpoints. I am following instructions from this page. In my case I don't have view hence I haven't created controller to specify the views and haven't added viewResolver in my AppConfig.java
After implementation it correctly shows the access denied error upon calling a secured REST endpoint. But even though I specify username/password in the request header I get the access denied error. I am testing in postman setting username/password in Basic Auth. What am I missing any idea?
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();
来源:https://stackoverflow.com/questions/34002878/securing-rest-endpoint-using-spring-security