如何在使用 spring 安全性的 spring 引导应用程序中跳过对 HAL 浏览器的授权
How to skip authorization for HAL browser in a spring boot application that make use of spring security
我想让 HAL 浏览器跳过对 spring 启动应用程序的授权。我正在使用 Spring 安全授权。
这是 build.gradle 文件
中条目的快照
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
我的 Spring 引导应用程序在端口 2128 上运行
http://localhost:2128/browser/index.html 将在实施 spring 安全性之前打开 HAL 浏览器。
我尝试在下面给出的 SecurityConfiguration class 的配置方法中添加 .antMatchers("/browser/index.html").permitAll()** 。我还尝试覆盖 public void configure(WebSecurity web) 方法以忽略 URL
背景 : HAL 浏览器在我实施 Spring 安全授权之前工作。它在实施 spring 安全措施后停止工作。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new AuthorizationFilter(authenticationManager(), userRepository))
.authorizeRequests()
// configure access rules
.antMatchers("/browser/index.html**").permitAll()
.anyRequest().authenticated();
http.headers().frameOptions().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/browser/index.html");
}
}
public class AuthorizationFilter extends BasicAuthenticationFilter {
public static final String HEADER_STRING_REMOTE_USER = "Remote-User";
/**
* Security pipe line is composed of different filters so we need to delegate to the rest of the pipeline.
*
* @param request
* @param response
* @param chain
* @throws IOException
* @throws ServletException
*/
@Override
protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
// Read the Authorization header, where we get the userId
String userId = request.getHeader(HEADER_STRING_REMOTE_USER);
// If header does not contain userId or is null delegate to Spring impl and exit
if (userId == null) {
chain.doFilter(request, response);
return;
}
// If userId is present, try grab user principal from database and perform authorization
Authentication authentication = getUsernamePasswordAuthentication(userId);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Continue filter execution
chain.doFilter(request, response);
}
private Authentication getUsernamePasswordAuthentication (String userId) {
// Search in the DB if we find the user by userId
// If so, then grab user details and create spring auth token using username, pass, authorities/roles
if (userId != null) {
List user = userRepository.findByUserId(userId);
UserPrincipal principal = new UserPrincipal(user.get(0));
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities());
return auth;
}
return null;
}
}
有没有人遇到过类似的问题...
我最后做的是使用 spring 个活动配置文件进行管理。
有关 spring 个人资料的更多信息,请参阅 link
我为 "secure" 配置文件启用了 Spring 安全性并为 "dev" 配置文件禁用了它。因此,在 "dev" 配置文件中,HAL 浏览器可以在没有任何安全中断的情况下工作。
@Configuration
@EnableWebSecurity
@Profile("secure")
public class WebSecurityConfigEnable extends WebSecurityConfigurerAdapter {
@Autowired
UserPrincipalDetailsService userPrincipalDetailsService;
private UserRepository userRepository;
@Value("${spring.profiles.active}")
private String activeProfile;
public WebSecurityConfigEnable (UserPrincipalDetailsService
userPrincipalDetailsService, UserRepository userRepository) {
this.userPrincipalDetailsService = userPrincipalDetailsService;
this.userRepository = userRepository;
}
@Override
protected void configure (AuthenticationManagerBuilder auth) throws
Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Override
protected void configure (HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> new
CorsConfiguration().applyPermitDefaultValues())
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new AuthorizationFilter(authenticationManager(),
userRepository, activeProfile))
.authorizeRequests()
// configure access rules
.anyRequest().authenticated();
}
@Bean
DaoAuthenticationProvider daoAuthenticationProvider () {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);
return daoAuthenticationProvider;
}
@Bean
PasswordEncoder passwordEncoder () {
return new BCryptPasswordEncoder();
}
}
对于 运行 "dev" 配置文件中的应用程序
java -jar -Dspring.profiles.active=dev build\libs\springApp-0.1.1-SNAPSHOT.jar
我想让 HAL 浏览器跳过对 spring 启动应用程序的授权。我正在使用 Spring 安全授权。
这是 build.gradle 文件
中条目的快照 implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
我的 Spring 引导应用程序在端口 2128 上运行
http://localhost:2128/browser/index.html 将在实施 spring 安全性之前打开 HAL 浏览器。 我尝试在下面给出的 SecurityConfiguration class 的配置方法中添加 .antMatchers("/browser/index.html").permitAll()** 。我还尝试覆盖 public void configure(WebSecurity web) 方法以忽略 URL
背景 : HAL 浏览器在我实施 Spring 安全授权之前工作。它在实施 spring 安全措施后停止工作。
@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilter(new AuthorizationFilter(authenticationManager(), userRepository)) .authorizeRequests() // configure access rules .antMatchers("/browser/index.html**").permitAll() .anyRequest().authenticated(); http.headers().frameOptions().disable(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/browser/index.html"); } }
public class AuthorizationFilter extends BasicAuthenticationFilter { public static final String HEADER_STRING_REMOTE_USER = "Remote-User"; /** * Security pipe line is composed of different filters so we need to delegate to the rest of the pipeline. * * @param request * @param response * @param chain * @throws IOException * @throws ServletException */ @Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // Read the Authorization header, where we get the userId String userId = request.getHeader(HEADER_STRING_REMOTE_USER); // If header does not contain userId or is null delegate to Spring impl and exit if (userId == null) { chain.doFilter(request, response); return; } // If userId is present, try grab user principal from database and perform authorization Authentication authentication = getUsernamePasswordAuthentication(userId); SecurityContextHolder.getContext().setAuthentication(authentication); // Continue filter execution chain.doFilter(request, response); } private Authentication getUsernamePasswordAuthentication (String userId) { // Search in the DB if we find the user by userId // If so, then grab user details and create spring auth token using username, pass, authorities/roles if (userId != null) { List user = userRepository.findByUserId(userId); UserPrincipal principal = new UserPrincipal(user.get(0)); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); return auth; } return null; } }
有没有人遇到过类似的问题...
我最后做的是使用 spring 个活动配置文件进行管理。
有关 spring 个人资料的更多信息,请参阅 link
我为 "secure" 配置文件启用了 Spring 安全性并为 "dev" 配置文件禁用了它。因此,在 "dev" 配置文件中,HAL 浏览器可以在没有任何安全中断的情况下工作。
@Configuration
@EnableWebSecurity
@Profile("secure")
public class WebSecurityConfigEnable extends WebSecurityConfigurerAdapter {
@Autowired
UserPrincipalDetailsService userPrincipalDetailsService;
private UserRepository userRepository;
@Value("${spring.profiles.active}")
private String activeProfile;
public WebSecurityConfigEnable (UserPrincipalDetailsService
userPrincipalDetailsService, UserRepository userRepository) {
this.userPrincipalDetailsService = userPrincipalDetailsService;
this.userRepository = userRepository;
}
@Override
protected void configure (AuthenticationManagerBuilder auth) throws
Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Override
protected void configure (HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> new
CorsConfiguration().applyPermitDefaultValues())
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new AuthorizationFilter(authenticationManager(),
userRepository, activeProfile))
.authorizeRequests()
// configure access rules
.anyRequest().authenticated();
}
@Bean
DaoAuthenticationProvider daoAuthenticationProvider () {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);
return daoAuthenticationProvider;
}
@Bean
PasswordEncoder passwordEncoder () {
return new BCryptPasswordEncoder();
}
}
对于 运行 "dev" 配置文件中的应用程序
java -jar -Dspring.profiles.active=dev build\libs\springApp-0.1.1-SNAPSHOT.jar