我有一个已经用JWT保护的spring Boot 应用程序,我想用内存中的基本身份验证用户保护spring执行器端点,所以我修改了Security config类以包括2个方法
Spring版本2.6.4
问题是
当我将“ActuatorSecurityConfigurerAdapter”顺序设置为-1并使用user 1进行测试时:user 1出现此错误,我的API变得不安全
JwtAuthenticationEntryPoint: Responding with unauthorized error. Message - Full authentication is required to access this resource
当我将“ActuatorSecurityConfigurerAdapter”顺序设置为2时,我可以使用JWT访问两个端点
安全配置类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true)
public class SecurityConfig {
@Order(1)
@Configuration
public class ApiSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
private final CustomUserDetailsServiceImpl customUserDetailsService;
private final JwtAuthenticationEntryPoint unauthorizedHandler;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public ApiSecurityConfigurationAdapter(CustomUserDetailsServiceImpl customUserDetailsService, JwtAuthenticationEntryPoint unauthorizedHandler, JwtAuthenticationFilter jwtAuthenticationFilter) {
this.customUserDetailsService = customUserDetailsService;
this.unauthorizedHandler = unauthorizedHandler;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(Endpoints.AUTH_ENDPOINT+"/**").permitAll()
.anyRequest()
.authenticated();
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
}
@Order(2)
@Configuration
public class ActuatorSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
AuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").hasRole("MODERATOR")
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1"))
.authorities("MODERATOR");
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
1条答案
按热度按时间juzqafwq1#
问题已解决
1.我为执行器安全性输入Order(1),为API的其余部分输入Order(2
1.要使用内存中的用户,我必须为ROLE_MODERATOR等权限添加“ROLE_”前缀,并在HTTP安全方法中添加.hasRole(“MODERATOR”)
这是最终的SecurityConfig.class