I'm developing a spring boot application which serves both RESTful API and Spring MVC web pages (with thymeleaf template). The web pages and RESTful API are protected by Spring OAuth2 SSO. But when I try to access the RESTful API from Spring RestTemplate in my Java client, I always get the status code of 302 and the response body that contains the contents of the authorization web page. That means, the restTemplate is "redirected" to the authorization page rather than to access the API with the access token.
here are the code and the configurations:
server:
port: 8888
security:
basic:
enabled: false
ignored: /welcome,/favicon.ico,/index.html,/signup,/assets/**,/js/**,/css/**,/webjars/**
sessions: ALWAYS
oauth2:
sso:
loginPath: /login
....
security:
basic:
enabled: false
oauth2:
client:
accessTokenUri: http://jx201.local:8043/uaa/oauth/token
userAuthorizationUri: http://jx201.local:8043/uaa/oauth/authorize
clientId: payment-gateway
clientSecret: 123456
....
SecurityConfig.java (annotated with @Configuration and @EnableOAuth2Sso):
http
.logout().logoutUrl("/logout").logoutSuccessUrl("/welcome").and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository());
When I use above java configuration, when trying to access my resources, like /payment/api/v1/status, the restTemplate (instance of OAuth2RestTemplate) always gets http code 302 and the content of the authorization page.
But if I use below code:
http.antMatcher("/assets/**").anonymous()
.and().antMatcher("/**").authorizeRequests()
.and().csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/[a-z0-9A-Z]*/api/v[0-9]*/.*", null);
@Override
public boolean matches(HttpServletRequest request) {
if(allowedMethods.matcher(request.getMethod()).matches()|| apiMatcher.matches(request)) {
return false;
}
return true;
}
})
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.logout().logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/welcome");
my resources, for example, /payment/api/v1/status, isn't protected by OAuth2&SSO
So the question is: how can I configure the spring security to make the rest resources accessible from both restTemplate and Spring MVC?
Thanks a lot!