spring - 我们能否根据 Mediatype 加载不同的安全配置,即一种 REST 和一种用于 Web?
问题描述
我已经开发了一个常规的 spring mvc 应用程序,并且想添加一些用于开发移动应用程序的 rest 控制器。我已经编写了休息控制器和多弹簧安全配置。
问题是,它们是优先的,因此两者都同时加载,整个应用程序都崩溃了。我想根据它收到的请求类型来使用一个,例如,如果我从 Postman 请求,Rest API 安全配置应该可以工作,如果我们使用网络,网络安全配置应该可以工作。
这是我的实现,我不知道如何实现,请提出正确的方法。由于分离整个 Thymeleaf 和 MVC 控制器,并且在这个阶段完全与 Angular 一起移动是不可能的。
请注意,我们在/v1/ap1/ ** 中定义了所有 rest api,所有其他 mvc 部分都在 / **
任何意见、建议将不胜感激,因为 3 天以来我的日子都快要死了。提前致谢
@Configuration
@EnableWebSecurity
public class SecurityConfig {
// ... other codes
@Configuration
@Order(1)
public static class RestAPISecurity extends WebSecurityConfigurerAdapter {
//.. other codes
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/signin/**").permitAll()
.antMatchers("/api/v1/**").hasAnyAuthority("ADMIN", "USER")
.antMatchers("/api/users/**").hasAuthority("ADMIN")
.antMatchers("/api/v1/**").authenticated()
.antMatchers("/login", "/logout", "/register", "/j_spring_security_check").permitAll()
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).accessDeniedHandler(new CustomAccessDeniedHandler());
}
// .. other codes
@Configuration
@Order(2)
public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {
//.. other codes
// form login and other MVC stuffs
}
}
解决方案
您可以为第一个 spring 安全过滤器链添加请求匹配器,其他所有内容都转到第二个链
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(httpServletRequest -> {
String userAgent = httpServletRequest.getHeader("User-Agent");
//If you want to check based on content type
String contentType = httpServletRequest.getContentType();
return userAgent.contains("....")
//check what value postman sends as user agent and use it
})
.sessionManagement()
....
}
推荐阅读
- python - 为什么我的 JupyterLab 笔记本代码控制台没有按应有的方式显示“命令历史记录”?
- azure - 将 Bot 连接到 Slack Clarification 的提交凭证步骤
- c++ - 快速将 2 个双精度数组交错为具有 2 个浮点数和 1 个 int(循环不变)成员的结构数组,使用 SIMD 双精度->浮点数转换?
- ubuntu - composer的安装方法有什么区别?
- reactjs - 如何在生产中部署 js?
- javascript - 使用 jQuery 将数据排序添加到现有数据表
- python - 正确转换图像以在 blob_log 中使用
- vim - 如何让 Vim 突出显示匹配的 <>?
- javascript - 创建在任务列表中应用过滤器的方法
- python - Python 中的 input() 函数可以动态检测输入的数据类型吗?