久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

帶有 Angular 6 的 Spring Boot JWT CORS

Spring Boot JWT CORS with Angular 6(帶有 Angular 6 的 Spring Boot JWT CORS)
本文介紹了帶有 Angular 6 的 Spring Boot JWT CORS的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我在我的 Spring Boot 應用程序中使用 JWT.當我嘗試從 Angular 6 客戶端登錄時,出現 CORS 錯誤

I am using JWT in my Spring Boot app. When I try to login from the Angular 6 client, I get the CORS error

Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我嘗試為 "Access-Control-Allow-Origin 添加標頭,我什至嘗試使用一些 chrome 擴展,但仍然無法繞過 CORS.我可以使用 Postman 訪問登錄 API 和獲取令牌.

I tried adding headers for "Access-Control-Allow-Origin, I even tried using some chrome extensions and still it couldn't bypass the CORS. I can access the login API with Postman and get the token.

Spring Boot 類

Spring Boot Classes

WebSecurityConfig.java

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private UserDetailsService userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurityConfig(@Qualifier("customUserDetailsService") UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

        @Override
    protected void configure(HttpSecurity http) throws Exception {

            http.csrf().disable().authorizeRequests()
                    .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                    .addFilter(new JWTAuthorizationFilter(authenticationManager()));
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

WebConfig.java

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping( "/**" )
                .allowedOrigins( "http://localhost:4200" )
                .allowedMethods( "GET", "POST", "DELETE" )
                .allowedHeaders( "*" )
                .allowCredentials( true )
                .exposedHeaders( "Authorization" )
                .maxAge( 3600 );
    }

}

JWTAuthorization.java 授予用戶訪問權限的類

JWTAuthorization.java the class that gives access to user

@Order(Ordered.HIGHEST_PRECEDENCE)
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(HEADER_STRING);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");

        if (header == null || !header.startsWith(TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }


        UsernamePasswordAuthenticationToken authenticationToken = getAuthenticationToken(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);



        chain.doFilter(request, response);

    }



    private UsernamePasswordAuthenticationToken getAuthenticationToken(HttpServletRequest request){
        String token = request.getHeader(HEADER_STRING);

        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();
            System.out.println(user);
            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }
}

JWTAuthenticationFilter.java 處理登錄請求并返回令牌的類

JWTAuthenticationFilter.java the class that handles the login request and returns the token

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(),User.class);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            user.getUsername(),
                            user.getPassword())
                    );

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String username = ((org.springframework.security.core.userdetails.User) authResult.getPrincipal()).getUsername();
        String token = Jwts
                .builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        System.out.println("TOKEN: " + token);

        String bearerToken = TOKEN_PREFIX + token;
        response.getWriter().write(bearerToken);
        response.addHeader(HEADER_STRING, bearerToken);

    }
}

有效的郵遞員示例

這是我發出登錄請求的方式,但會出現錯誤

Here is how I make the post request to login that gives me the error

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  public apiURL:string="http://localhost:8082";

  constructor(private httpClient:HttpClient) { }

  validateUser(user:User){

    let userData = "username=love"+ "&password=12345" + "&grant_type=password";
    let reqHeader = new HttpHeaders({ 'Content-Type': 'application/json' });

    const data = new FormData();
    data.append("username", user.username);
    data.append("password", user.password);

    console.log(data);


    return this.httpClient.post<User>(this.apiURL + '/login',data,{headers:reqHeader});
  }

  storeToken(token: string) {
    localStorage.setItem("token", token);
  }
  getToken() {
    return localStorage.getItem("token");
  }
  removeToken() {
    return localStorage.removeItem("token");
  }
}

還有 Angular 中的 User 界面

Also the User interface in Angular

export interface User {
  username:string;
  password:string;
}

推薦答案

由于消息是關于您的 preflight 請求,即 OPTIONS 請求,

Since message is about your preflight request i.e. OPTIONS request,

我猜,你需要在服務器端/Spring Boot 代碼上做兩件事,

I guess, you need to do two things on server side / Spring Boot code ,

  1. 從身份驗證過濾器返回 OK,因此需要在 attemptAuthentication 方法中添加以下內容作為第一個檢查,即不對預檢請求進行真正的身份驗證,
  1. Return OK from Authentication filter so need to add below in attemptAuthentication method as first check i.e. don't do real authentication for preflight requests,

if (CorsUtils.isPreFlightRequest(httpServletRequest)) {httpServletResponse.setStatus(HttpServletResponse.SC_OK);返回新的身份驗證();//無論你的令牌實現類是什么 - 返回它的一個實例
}

CorsUtils 是 - org.springframework.web.cors.CorsUtils

CorsUtils is - org.springframework.web.cors.CorsUtils

  1. 讓 Spring Security 將 Authorized Options 請求輸入到系統中,因此在 Security Config 中添加這些行,

.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

您也可以允許未經授權的 OPTIONS 請求,但我想這不是一個好主意.此外,如果可能,請嘗試將/**"縮小到特定的 URL.

You can allow unauthorized OPTIONS requests too but I guess , that wouldn't be a good idea. Also, try to narrow down "/**" to specific URLs if possible.

這篇關于帶有 Angular 6 的 Spring Boot JWT CORS的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 国产精品毛片av一区 | 国产精品欧美一区二区三区不卡 | 久草资源网站 | 亚洲精品久久久久久国产精华液 | 一级做a爰片久久毛片免费看 | 黄一级| 亚洲精品视频在线播放 | 黄色免费在线网址 | 91成人午夜性a一级毛片 | 九九久久在线看 | 亚洲视频免费观看 | 久久精品一区 | 久久久久国产一级毛片高清网站 | 99国产精品视频免费观看一公开 | 中文字幕一区二区三区四区不卡 | 91豆花视频 | 欧美一区二区在线观看 | 亚洲视频在线播放 | 国产91网站在线观看 | 久久精品一区二区三区四区 | 久久久久久亚洲精品 | 国产做a爱免费视频 | 国产精品视频一区二区三区不卡 | 国产精品无码久久久久 | 国产免费av网 | 国产精品亚洲一区二区三区在线观看 | 在线免费观看a级片 | 精品一区二区三区不卡 | 在线观看亚洲一区二区 | www.色.com| 欧美黄色小视频 | 欧美亚洲第一区 | 九九久久久 | 欧美成人猛片aaaaaaa | av在线一区二区三区 | 久久精品小视频 | 精品国产免费人成在线观看 | 国产一区中文字幕 | 国产传媒在线观看 | 在线观看免费黄色片 | 狠狠操狠狠干 |