前端请求 Authorization
必须是正确并且没过期,或不设置这个值才可以,这是为什么,我 SecurityConfig
中已经配置放行了。
Authorization
不设置这个值都可以,为什么错误不行,怎么设置才可以放行中的链接错误也可以,错误和不设置这个值 @AuthenticationPrincipal Jwt jwt
为空就行了
SecurityConfig.java
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class SecurityConfig {
@Value("${jwt.public.key}")
RSAPublicKey key;
@Value("${jwt.private.key}")
RSAPrivateKey priv;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/test/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> {
oauth2.jwt(Customizer.withDefaults());
});
return http.build();
}
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
@Bean
JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
TestController.java
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping("/list")
public Map<String, Object> listCart(@AuthenticationPrincipal Jwt jwt, HttpServletRequest req) {
Map<String, Object> map = new HashMap<>();
if (jwt != null) {
map.put("id", jwt.getId());
}
return map;
}
}
前端请求
$fetch('http://localhost:8080/test/list', {
method: 'POST',
headers: {
Authorization: 'Bearer 1111111111',
}
})
你非要这么实现,你就改写这个类注入就行了,这里获取token以后,根据url过滤规则判断一下,如果是允许可以匿名访问的,最简单的办法就是直接返回空就行了
实际上他这个处理远比你想要实现的功能正确得多,是前端入参不规范
我不知道难在哪
修改为默认实现类