繁体   English   中英

Spring 启动 + 与 Angular 应用程序通信的安全配置

[英]Spring Boot + Security configuration for communication with Angular app

我在域 A 上运行了 spring 启动应用程序。它的目的是公开一些 REST 端点。

另外,我有 angular 8 应用程序。 它可以部署在同一个域 A 或其他域 B 中。spring 启动应用程序知道 angular 应用程序部署在哪个域上。

我需要配置 Spring 安全性,因此它将仅接受来自 angular 应用程序的特定端点上的请求。 而且,一些端点需要具有角色意识

例如:

  • /api/v1/resources/** - 应仅来自 angular 应用程序
  • /api/v1/resources/admin/** - 应该只来自 angular 应用并且用户应该具有管理员角色
  • /api/v1/payments/** - 这不仅可以接受来自 angular 应用程序的请求(例如商家回调)

我将非常感谢有关此最佳方法的一些建议

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();
}

您可以创建 HeaderFilter.class 并在 doFilter() 方法内部实现如下所示。

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();
                }
            }
        }

    }
}

您还可以在 securityconfig.java 中为 ADMIN 访问添加基于角色的附加身份验证

在从 WebSecurityConfigurerAdapter ( org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter )扩展的 WebSecurityConfig class 中,编辑您的配置 mwthod

@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()           
            ...
            ...
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM