Spring Security Jwt Token Разрешить все параметры метода при запросе формы угловой - PullRequest
0 голосов
/ 27 февраля 2019

Я не знаю, в чём дело, я везде проверил онлайн, похоже, что я тоже, но я получаю эту проблему:

Я запрашиваю приложение My Angular, используя HttpClient с угловым перехватчикомдля setHeader, потому что мой Java Rest API использует JWT для аутентификации и нуждается в токене в заголовке, чтобы он получал и проверял пользовательский запрос, потому что угловой перехватчик не работает должным образом.Я получаю нулевой токен на стороне Java и получаю сообщение об ошибке.Пожалуйста, помогите мне с этим.

Наконец, я обнаружил, что это может быть проблемой безопасности пружин, потому что я отладил и обнаружил, что опция запроса запрашивает все фильтры и не имеет заголовка, поэтому он показывает токен и генерирует исключенияесли вариант метода запрос обойти и разрешить, то моя проблема может решить

Пружинная загрузка Конфигурация безопасности

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);
  }
}

Вызов Mathod

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

Ошибка консоли Java Spring Boot

backend Java Console Error

1 Ответ

0 голосов
/ 27 февраля 2019

Угловой перехватчик выглядит хорошо, но в консоли вашего браузера есть ошибка CORS policy.Ваше угловое приложение работает на порту 4200, а ваш бэкэнд работает на 8095 (разные хосты).

Я не знаю spring-boot, но после просмотра документации вы должны добавить в Cors политикуБэкэнд-приложение (отличное для среды производства и разработки):

enter image description here

Подробнее вы можете прочитать здесь: https://spring.io/guides/gs/rest-service-cors/

теперь вашзапрос на /allUser не отправляется ... После устранения проблемы с CORS все должно работать нормально

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...