I have the spring boot application running on the domain A.It purpose is to expose some REST endpoints.
Also, I have angular 8 application. It could be deployed on the same domain A, or in other domain B. The spring boot app is aware of on which domain is angular app deployed.
I need to configure Spring security,so it will accept requests on particular endpoints ONLY from the angular app. But also, some of the endpoints need to be role-aware
For example:
I would highly appreciate some pieces of advice on the best approach for this
You can achieve this by applying URL specific filter in securityConfig.java class where you have extended WebSecurityConfigurerAdapter class also you need to pass one custom header from your Angular app.
@Autowired
private HeaderFilter headerFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v1/resources/**")
.addFilterBefore(headerFilter, BasicAuthenticationFilter.class)
.authorizeRequests()
.anyRequest().authenticated();
}
You can create HeaderFilter.class and inside doFilter() method implement like below.
public class HeaderFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
request.getHeader("YOUR_CUSTOM_HEADER");
//get Angular app specific header and it's value whether it is correct then true else stop filter chain.
if(FOUND){
chain.doFilter(request, response);
} else {
throw Exception();
}
}
}
}
}
You can also add ROLE BASED additional authentication for ADMIN access in securityconfig.java
In your WebSecurityConfig class which extends from WebSecurityConfigurerAdapter ( org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
) edit your configure mwthod as this
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/v1/resources/admin/**").hasRole("admin")
.antMatchers("/api/v1/payments/**").permitAll()
.anyRequest().authenticated()
...
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.