为啥我没有得到授权标头?
Posted
技术标签:
【中文标题】为啥我没有得到授权标头?【英文标题】:Why I don't get authorization header?为什么我没有得到授权标头? 【发布时间】:2021-01-05 01:09:04 【问题描述】:我使用 Spring 框架。如果我使用邮递员发送请求,我会得到授权标头,但如果我使用 Axois,我不会得到它。有什么问题?
Axois 发送:
axios(
method: 'get',
url: 'http://localhost:8081/api/posts',
headers: 'Authorization': 'Bearer_' + localStorage.getItem("username") // Cookies.get('Token')
)
春天来了
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**")
.allowedHeaders("*")
.exposedHeaders("Authorization", "authorization")
.allowedOrigins("*")
.allowedMethods("*")
.allowCredentials(false).maxAge(3600);;
Spring 安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception
http
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(LOGIN_ENDPOINT, REGISTRATION_ENDPOINT).permitAll()
.antMatchers(ADMIN_ENDPOINT).hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider));
在此处获取标题:
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException
HttpServletRequest httpRequest = (HttpServletRequest) req;
Map<String, List<String>> headersMap = Collections.list(httpRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(
Function.identity(),
h -> Collections.list(httpRequest.getHeaders(h))
));
Postman request
Headers with postman
Headers with Axios
【问题讨论】:
【参考方案1】:我添加了 Bean:
@Bean
CorsConfigurationSource corsConfigurationSource()
final UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config.applyPermitDefaultValues());
return source;
【讨论】:
以上是关于为啥我没有得到授权标头?的主要内容,如果未能解决你的问题,请参考以下文章
laravel 4:为啥 Request::header() 没有得到指定的标头?