質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ionic

Ionicは、クロスプラットフォームに対応したモバイルアプリ開発のためのオープンソースUIフレームワークです。iOSやAndroid、Webのアプリケーションを1つのコードベースで開発できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

Q&A

解決済

2回答

1757閲覧

IonicからSpring Webアプリケーションにアクセスしたい

Linkey

総合スコア77

Ionic

Ionicは、クロスプラットフォームに対応したモバイルアプリ開発のためのオープンソースUIフレームワークです。iOSやAndroid、Webのアプリケーションを1つのコードベースで開発できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

1グッド

2クリップ

投稿2020/10/07 13:54

編集2020/10/14 13:58

ionicとJavaを勉強しているものです。

▼開発環境
・Windows PC:
ionicを実装

・Mac PC:
STS(Spring Tool Suite)でWebアプリケーション実装
DockerでUbuntuを起動してionicからリクエストを受け付ける

動作確認のために以下のように実装しました。

typescript

1 2import { HttpClient, HttpHeaders } from '@angular/common/http'; 3@Component({ 4 selector: 'app-root', 5 templateUrl: 'app.component.html', 6 styleUrls: ['app.component.scss'] 7}) 8export class AppComponent { 9 constructor( 10 private httpClient: HttpClient, 11 ) { 12 this.initializeApp(); 13 } 14 15 initializeApp() { 16 this.httpClient.post("http://XXX.XXX.X.X:8080/getToken", {},{ 17 headers : new HttpHeaders({ 18 'Access-Control-Allow-Origin': '*', 19 'Content-Type': 'application/json', 20 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT', 21 'Accept': 'application/json', 22 'content-type': 'application/json' 23 }) 24 }) 25 .subscribe((response) => { 26 console.log("レスポンス結果:" + JSON.stringify(response)); 27 }) 28 } 29}

docker-compose.yml

yaml

1version: '3' 2 3services: 4 #ubuntu 5 app: 6 image: ubuntu 7 command: /bin/bash 8 tty: true 9 ports: 10 - "127.0.0.1:8100:8100" 11 - "127.0.0.1:8080:8080" 12 expose: 13 - "8100" 14 - "8080" 15 16 # MySQL 17 db: 18 image: mysql:5.7 19 container_name: mysql_host 20 environment: 21 MYSQL_ROOT_PASSWORD: password 22 MYSQL_DATABASE: sample_db 23 MYSQL_USER: admin 24 MYSQL_PASSWORD: password 25 TZ: 'Asia/Tokyo' 26 command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci 27 volumes: 28 - ./docker/db/data:/var/lib/mysql 29 - ./docker/db/my.cnf:/etc/mysql/conf.d/my.cnf 30 - ./docker/db/sql:/docker-entrypoint-initdb.d 31 ports: 32 - 3306:3306 33 build: 34 context: . 35 dockerfile: Dockerfile1 36

Java

1@Controller 2public class UserController { 3 @RequestMapping(value = "/getToken", method = RequestMethod.POST, produces="application/json; charset=UTF-8") 4 public ResponseEntity<Object> getToken(HttpServletRequest request, CsrfToken token) { 5 // リクエストを受け付けられるかを確認する 6 System.out.println("取得したトークン" + token.getToken()); 7 return new ResponseEntity<>("{}", HttpStatus.OK); 8 } 9}

Java

1@Configuration 2@EnableWebSecurity 3public class AppSecurityConfig extends WebSecurityConfigurerAdapter { 4 @Override 5 protected void configure(HttpSecurity http) throws Exception { 6 // URLアクセス設定 7 http.authorizeRequests().mvcMatchers("/getToken").permitAll() 8 .and().cors().configurationSource(this.corsConfigurationSource()); 9 } 10 @Bean 11 public org.springframework.web.cors.CorsConfigurationSource corsConfigurationSource() { 12 CorsConfiguration configuration = new CorsConfiguration(); 13 configuration.setAllowCredentials(true); 14 configuration.setAllowedOrigins(Arrays.asList("http-nio-XXX.XXX.X.X-8080", "http-nio-XXX.XXX.X.X-8100")); 15 configuration.setAllowedHeaders(Arrays.asList( 16 "Access-Control-Allow-Headers", 17 "Access-Control-Allow-Origin", 18 "Access-Control-Request-Method", 19 "Access-Control-Request-Headers", 20 "Cache-Control", 21 "Content-Type", 22 "Accept-Language")); 23 configuration.setAllowedMethods(Arrays.asList("GET", "POST")); 24 25 org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new org.springframework.web.cors.UrlBasedCorsConfigurationSource(); 26 source.registerCorsConfiguration("/**", configuration); 27 return source; 28 } 29 30}

【動作確認手順】
①STSを起動する。(ionicからのリクエストを待つ)
②Dockerを起動する(外部アクセスを許可)
③ng serveでアプリ起動

ionicを起動してリクエストを実行したところ以下のエラーとなってしまいました。
Access to XMLHttpRequest at 'http://XXX.XXX.X.X:8080/getToken' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORSについて調べてみたのですが、なかなか解決ができません。
アクセス許可設定についてお詳しい方がいましたらご回答いただけないでしょうか?

A-pZ👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

getTokenメソッドに@CrossOriginアノテーションを付与したところ解決できました。

投稿2021/04/11 06:36

Linkey

総合スコア77

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

動作確認ができていませんので見当違いかもしれませんが、CORSの登録がうまくいっていないようです。

  • HttpSecurityにてcors()を指定
  • UrlBasedCorsConfigurationSourceのregisterCorsConfigurationが必要

https://spring.pleiades.io/spring-security/site/docs/5.0.19.BUILD-SNAPSHOT/reference/html/cors.html

java

1@EnableWebSecurity 2public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 3 4 @Override 5 protected void configure(HttpSecurity http) throws Exception { 6 http.cors().and() // cors() を宣言 7 ... 8 } 9 10 @Bean 11 CorsConfigurationSource corsConfigurationSource() { 12 CorsConfiguration configuration = new CorsConfiguration(); 13 configuration.setAllowedOrigins(Arrays.asList("https://example.com")); 14 configuration.setAllowedMethods(Arrays.asList("GET","POST")); 15 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 16 source.registerCorsConfiguration("/**", configuration); // CORS設定を登録、が抜けているかも知れません。 17 return source; 18 } 19

投稿2020/10/14 04:07

A-pZ

総合スコア12011

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Linkey

2020/10/14 13:52

回答ありがとうございます。試してみましたがエラーは変わりませんでした。dockerの中身を変えてみたりいろいろ試しています。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問