代码之家  ›  专栏  ›  技术社区  ›  harkesh kumar

当Http请求时,角度拦截器未在头中设置令牌

  •  0
  • harkesh kumar  · 技术社区  · 7 年前

    我不知道出了什么事,我在网上到处查了一下,看起来和以前一样,但我发现了这个问题:

    我使用带有角度拦截器的HttpClient向setHeader请求我的角度应用程序,因为我的Java Rest API使用JWT进行身份验证,并且需要在header中使用一个令牌,这样它将获取并验证用户请求,因为角度拦截器工作不正常。我在Java端得到一个空标记,并得到一个错误。请帮帮我。

    最后,我发现它可能是spring安全性的问题,因为我调试后发现,option request all filter和它的dont have header所以它的showing token和throw异常 如果选项方法请求绕过并允许,则可能是我的问题将解决

    Spring boot安全配置

    package com.techprimers.security.jwtsecurity.config;
    
    import com.techprimers.security.jwtsecurity.security.JwtAuthenticationEntryPoint;
    import com.techprimers.security.jwtsecurity.security.JwtAuthenticationProvider;
    import com.techprimers.security.jwtsecurity.security.JwtAuthenticationTokenFilter;
    import com.techprimers.security.jwtsecurity.security.JwtSuccessHandler;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.ProviderManager;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    
    import java.util.Collections;
    
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @EnableWebSecurity
    @Configuration
    public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
    
    
        @Autowired
        private JwtAuthenticationProvider authenticationProvider;
        @Autowired
        private JwtAuthenticationEntryPoint entryPoint;
    
        @Bean
        public AuthenticationManager authenticationManager() {
            return new ProviderManager(Collections.singletonList(authenticationProvider));
        }
    
        @Bean
        public JwtAuthenticationTokenFilter authenticationTokenFilter() {
            JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
            filter.setAuthenticationManager(authenticationManager());
            filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
            return filter;
        }
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        }
    
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http.csrf().disable()
                    .authorizeRequests().antMatchers("**/rest/**").authenticated()
                    .and()
                    .exceptionHandling().authenticationEntryPoint(entryPoint)
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    
            http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
            http.headers().cacheControl();
    
    
    
        }
    }
    

    角截获码

    import { Injectable } from '@angular/core';
    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // add authorization header with jwt token if available
    
    
    
                console.log("i am inside");
    
                request = request.clone({
                    setHeaders: {
                        Accept: 'application/json',
                        Authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                });
    
    
            return next.handle(request);
        }
    }
    

    角服务

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ServiceService {
    
      constructor(private http: HttpClient) { }
    
      api_user_url = 'http://localhost:8095';
    
      getAllApiUsers(): Observable<any> {
        return this.http.get(this.api_user_url + "/allUser");
      }
    
      setUserLogin(obj):Observable<any>{
    
        return this.http.post(this.api_user_url +"/login", obj);
      }
    }
    

    呼叫马修

    public getAllUserList() {
    
        console.log("I am calling");
    
        this.service.getAllApiUsers()
          .subscribe(data => {
            this.alluser = data;
            console.log(data);
    
          })
      }
    

    浏览器网络

    Network Tab

    令牌的本地存储

    enter image description here

    浏览器控制台错误消息

    Browser Console

    Spring Boot Java控制台错误

    backend Java Console Error

    0 回复  |  直到 7 年前
        1
  •  0
  •   Krzysztof Raciniewski Eliseo    7 年前

    角度拦截器看起来不错,但在浏览器控制台中 CORS policy 错误。你的angular应用程序正在端口上运行 4200 你的后台正在运行 8095 (不同的主机)。

    我不知道 spring-boot 但是在检查完文档之后,您应该向后端应用程序添加一些cors策略(不同于生产和开发环境):

    enter image description here

    更多信息请阅读: https://spring.io/guides/gs/rest-service-cors/

    现在你的请求 /allUser 不发送。。。排除CORS问题后,一切都应该正常工作

    推荐文章