IonicとSpring Bootを勉強しているものです。
自宅のローカル環境でIonicで作成したAndroidアプリケーションを使ってSpring Tool Suiteで実装したJavaプログラムと通信できるかをテストしています。
通信確認できたらアクセス権限設定を行うためにSpring Securityも導入しています。
registration.page.ts
typescript
1 2import { HTTP } from '@ionic-native/http/ngx'; 3 4const HEADERS = { 5 "Content-Type": "application/json;" 6}; 7 8@Component({ 9 selector: 'app-registration', 10 templateUrl: './registration.page.html', 11 styleUrls: ['./registration.page.scss'], 12}) 13export class RegistrationPage implements OnInit { 14 15 constructor( 16 private http: HTTP, 17 ) { } 18 19 ngOnInit() { 20 } 21 22 register(){ 23 let name = "user1"; 24 let password = "password"; 25 26 let data = { 27 name: name, 28 password: password, 29 } 30 31 this.http.setDataSerializer('json'); 32 this.http.post('http://(MacのIPアドレス):8080/register', data, HEADERS).then((data) => { 33 alert("登録成功") 34 }).catch((error) => { 35 alert("登録エラー:" + JSON.stringify(error)) 36 }); 37 } 38 39} 40
SampleController.java
Java
1 @RequestMapping(value="/register", method=RequestMethod.POST, produces="application/json; charset=UTF-8") 2 public ResponseEntity<String> register(@Requestbody request){ 3 // まずはリクエストを受信できるかをチェックする 4 System.out.println("リクエスト受信しました。"); 5 6 // TODO 会員登録処理を実装する 7 8 return new ResponseEntity<>("{}", HttpStatus.OK); 9 } 10
AppSecurityConfig.java
Java
1@Configuration 2@EnableWebSecurity 3public class AppSecurityConfig extends WebSecurityConfigurerAdapter { 4 @Override 5 public void configure(WebSecurity web) throws Exception { 6 web.ignoring().antMatchers("/css/**", "/js/**"); 7 web.httpFirewall(new AppHttpFirewall(sessionRegistry)); 8 } 9 10 @Override 11 protected void configure(HttpSecurity http) throws Exception { 12 http.sessionManagement() 13 .maximumSessions(1) 14 .maxSessionsPreventsLogin(true) 15 .sessionRegistry(sessionRegistry()) 16 .and() 17 .sessionFixation().newSession(); 18 19 http.authorizeRequests() 20 .mvcMatchers(HttpMethod.GET, "/").permitAll() 21 .mvcMatchers(HttpMethod.POST, "/register", "/authenticate").permitAll() 22 .anyRequest().authenticated(); 23 24 http.formLogin() 25 .loginProcessingUrl("/authenticate") // ログイン処理URL 26 .failureHandler(new AppAuthenticationFailureHandler()) //認証失敗時 27 .successHandler(new AppAuthenticationSuccessHandler()) 28 .usernameParameter("name") 29 .passwordParameter("password") 30 .permitAll(); 31 } 32}
AppHttpFirewall.java
java
1public class AppHttpFirewall extends StrictHttpFirewall { 2 3// private static final Logger logger = LoggerFactory.getLogger("test_log"); 4 private SessionRegistry sessionRegistry; 5 6 public AppHttpFirewall(SessionRegistry sessionRegistry) { 7 super(); 8 this.sessionRegistry = sessionRegistry; 9 return; 10 } 11 12 @Override 13 public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException { 14 System.out.println("検知したリクエストURL:" + request.getRequestURL()); 15 16 String userId = ""; 17 String cookieCerfToken = null; 18 String userAgent = request.getHeader("user-agent"); 19 20 Cookie csrfToken = WebUtils.getCookie(request, "_csrf"); 21 if(Objects.nonNull(csrfToken)) { 22 cookieCerfToken = csrfToken.getValue(); 23 } 24 25 // セッションレジストリーからユーザー情報を取得しユーザIDを取得する 26 SessionInformation sessionInfo = sessionRegistry.getSessionInformation(request.getSession().getId()); 27 if(Objects.nonNull(sessionInfo)) { 28 Object principal = sessionInfo.getPrincipal(); 29 if(principal instanceof UserDetails) { 30 DMUser user = (DMUser) principal; 31 userId = user.getUser().getUserId(); 32 } 33 } 34 35 try { 36 return super.getFirewalledRequest(request); 37 } catch (RequestRejectedException e) { 38 // 認証情報をクリアする 39 SecurityContextHolder.clearContext(); 40 request.getSession().invalidate(); 41 // logger.error("リクエストURL不正") 42 return new FirewalledRequest(request) { 43 @Override 44 public void reset() { 45 return; 46 } 47 }; 48 } 49 } 50 51 @Override 52 public HttpServletResponse getFirewalledResponse(HttpServletResponse response) { 53 // TODO 自動生成されたメソッド・スタブ 54 return super.getFirewalledResponse(response); 55 } 56 57}
AppAuthenticationProvider.java
Java
1public class AppAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { 2 @Override 3 protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) 4 throws AuthenticationException { 5 System.out.println("ユーザー名:" + username); 6 System.out.println("パスワード:" + authentication.getCredentials().toString()); 7 8 // 動作確認のため一旦、例外をスローする 9 throw new AuthenticationException("ログインに失敗") { 10 11 /** 12 * 13 */ 14 private static final long serialVersionUID = 1L; 15 }; 16 } 17}
pom.xml
xml
1 2 (省略) 3 4<dependency> 5 <groupId>org.springframework.security</groupId> 6 <artifactId>spring-security-web</artifactId> 7 <version>5.3.4.RELEASE</version> 8</dependency> 9<dependency> 10 <groupId>org.springframework.security</groupId> 11 <artifactId>spring-security-config</artifactId> 12 <version>5.3.4.RELEASE</version> 13</dependency> 14 15 (省略)
Spring Tool SuiteにてTomcatを起動させて外部リクエストを受け付け可能な状態にした上で動作確認用のスマホにIonicで作成したAndroidアプリケーションをインストールしリクエストを実行を行ったところ以下のエラーとなりました。
登録エラー:
{"status":-1, "error":"There was an error with the request: failed to connect to /[MacのIPアドレス](port 8080): connect failed: ECONNREFUSED (Connection refused)"}
pom.xml からSpring Securityの設定を消すと接続できました。
調べてみたところMacで外部接続を受け付けるにはhostファイルに ホスト名.localの記載が必要ということなので
以下の設定をしました。
127.0.0.1 localhost (ホスト名).local
::1 localhost (ホスト名).local
上記の設定をしてMacを再起動してから試してみたのですが、リクエスト実行に失敗してしまいます。
Spring Securityを導入したときの設定が足りていないのでしょうか?
Spring Securityの設定に詳しい方がいましたらご回答いただけないでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。