teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

実際に書いたコードを追記します

2020/06/21 23:55

投稿

kachikata96
kachikata96

スコア28

title CHANGED
File without changes
body CHANGED
@@ -12,4 +12,389 @@
12
12
  やはり、eclipseに何かしらcurlの設定をしなくはいけないのでしょうか。
13
13
 
14
14
  まだ、springの理解が浅く支離滅裂な質問になってしまい申し訳ありませんが
15
- 考えられる原因を教えていただけたら幸いです。
15
+ 考えられる原因を教えていただけたら幸いです。
16
+
17
+ ```java
18
+ //REST用のサービスクラス
19
+
20
+ package com.example.demo.login.domain.service;
21
+
22
+ import java.util.List;
23
+
24
+ import com.example.demo.login.domain.model.User;
25
+
26
+ public interface RestService {
27
+
28
+ //1件登録用メソッド
29
+ public boolean insert(User user);
30
+
31
+ //1件検索用メソッド
32
+ public User selectOne(String userId);
33
+
34
+ //全件検索用メソッド
35
+ public List<User> selectMany();
36
+
37
+ //1件更新用メソッド
38
+ public boolean update(User user);
39
+
40
+ //1件削除用メソッド
41
+ public boolean delete(String userId);
42
+ }
43
+ ```
44
+
45
+ ```java
46
+ //JDBCを使うクラス
47
+
48
+ package com.example.demo.login.domain.service.jdbc;
49
+
50
+ import java.util.List;
51
+
52
+ import org.springframework.beans.factory.annotation.Autowired;
53
+ import org.springframework.beans.factory.annotation.Qualifier;
54
+ import org.springframework.stereotype.Service;
55
+ import org.springframework.transaction.annotation.Transactional;
56
+
57
+ import com.example.demo.login.domain.model.User;
58
+ import com.example.demo.login.domain.repository.UserDao;
59
+ import com.example.demo.login.domain.service.RestService;
60
+
61
+ @Transactional
62
+ @Service
63
+ public class RestServiceJdbcImpl implements RestService {
64
+
65
+ @Autowired
66
+ @Qualifier("UserDaoJdbcImpl")
67
+ UserDao dao;
68
+
69
+ //1件登録用メソッド
70
+ @Override
71
+ public boolean insert(User user) {
72
+
73
+ int result = dao.insertOne(user);
74
+
75
+ if(result == 0) {
76
+
77
+ return false;
78
+
79
+ } else {
80
+
81
+ return true;
82
+
83
+ }
84
+ }
85
+
86
+ //1件検索用メソッド
87
+ @Override
88
+ public User selectOne(String userId) {
89
+ return dao.selectOne(userId);
90
+ }
91
+
92
+ //全件検索用メソッド
93
+ @Override
94
+ public List<User> selectMany() {
95
+ return dao.selectMany();
96
+ }
97
+
98
+ //1件更新用メソッド
99
+ @Override
100
+ public boolean update(User user) {
101
+
102
+ int result = dao.updateOne(user);
103
+
104
+ if(result == 0) {
105
+
106
+ return false;
107
+
108
+ } else {
109
+
110
+ return true;
111
+
112
+ }
113
+ }
114
+
115
+ //1件削除用メソッド
116
+ @Override
117
+ public boolean delete(String userId) {
118
+
119
+ int result = dao.deleteOne(userId);
120
+
121
+ if(result == 0) {
122
+
123
+ return false;
124
+
125
+ } else {
126
+
127
+ return true;
128
+
129
+ }
130
+ }
131
+ }
132
+ ```
133
+
134
+ ```java
135
+ //REST用のコントローラークラス
136
+
137
+ package com.example.demo.login.controller;
138
+
139
+ import java.util.List;
140
+
141
+ import org.springframework.beans.factory.annotation.Autowired;
142
+ import org.springframework.web.bind.annotation.DeleteMapping;
143
+ import org.springframework.web.bind.annotation.GetMapping;
144
+ import org.springframework.web.bind.annotation.PathVariable;
145
+ import org.springframework.web.bind.annotation.PostMapping;
146
+ import org.springframework.web.bind.annotation.PutMapping;
147
+ import org.springframework.web.bind.annotation.RequestBody;
148
+ import org.springframework.web.bind.annotation.RestController;
149
+
150
+ import com.example.demo.login.domain.model.User;
151
+ import com.example.demo.login.domain.service.RestService;
152
+
153
+ @RestController
154
+ public class UserRestController {
155
+
156
+ @Autowired
157
+ RestService service;
158
+
159
+ /**
160
+ * ユーザー全件取得
161
+ */
162
+ @GetMapping("/rest/get")
163
+ public List<User> getUserMany() {
164
+
165
+ // ユーザー全件取得
166
+ return service.selectMany();
167
+ }
168
+
169
+ /**
170
+ * ユーザー1件取得
171
+ */
172
+ @GetMapping("/rest/get/{id:.+}")
173
+ public User getUserOne(@PathVariable("id") String userId) {
174
+
175
+ // ユーザー1件取得
176
+ return service.selectOne(userId);
177
+ }
178
+
179
+ /**
180
+ * ユーザー1件登録
181
+ */
182
+ @PostMapping("/rest/insert")
183
+ public String postUserOne(@RequestBody User user) {
184
+
185
+ // ユーザーを1件登録
186
+ boolean result = service.insert(user);
187
+
188
+ String str = "";
189
+
190
+ if(result == true) {
191
+
192
+ str = "{\"result\":\"ok\"}";
193
+
194
+ } else {
195
+
196
+ str = "{\"result\":\"error\"}";
197
+
198
+ }
199
+
200
+ // 結果用の文字列をリターン
201
+ return str;
202
+ }
203
+
204
+ /**
205
+ * ユーザー1件登録
206
+ */
207
+ @PutMapping("/rest/update")
208
+ public String putUserOne(@RequestBody User user) {
209
+
210
+ // ユーザーを1件登録
211
+ boolean result = service.update(user);
212
+
213
+ String str = "";
214
+
215
+ if(result == true) {
216
+
217
+ str = "{\"result\":\"ok\"}";
218
+
219
+ } else {
220
+
221
+ str = "{\"result\":\"error\"}";
222
+
223
+ }
224
+
225
+ // 結果用の文字列をリターン
226
+ return str;
227
+ }
228
+
229
+ @DeleteMapping("/rest/delete/{id:.+}")
230
+ public String deleteUserOne(@PathVariable("id") String userId) {
231
+
232
+ // ユーザーを1件削除
233
+ boolean result = service.delete(userId);
234
+
235
+ String str = "";
236
+
237
+ if(result == true) {
238
+
239
+ str = "{\"result\":\"ok\"}";
240
+
241
+ } else {
242
+
243
+ str = "{\"result\":\"error\"}";
244
+
245
+ }
246
+
247
+ // 結果用の文字列をリターン
248
+ return str;
249
+ }
250
+ }
251
+ ```
252
+
253
+ ```java
254
+ //RESTサービスのみCSRF対策を無効にするためにRequestMatcherを実装したクラス
255
+
256
+ package com.example.demo;
257
+
258
+ import javax.servlet.http.HttpServletRequest;
259
+
260
+ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
261
+ import org.springframework.security.web.util.matcher.RequestMatcher;
262
+
263
+ public class RestMatcher implements RequestMatcher {
264
+
265
+ //マッチャー
266
+ private AntPathRequestMatcher matcher;
267
+
268
+ //コンストラクタ
269
+ public RestMatcher(String url) {
270
+ super();
271
+ matcher = new AntPathRequestMatcher(url);
272
+ }
273
+
274
+ //URLのマッチ条件
275
+ @Override
276
+ public boolean matches(HttpServletRequest request) {
277
+
278
+ // GETならCSRFのチェックはしない
279
+ if("GET".equals(request.getMethod()))
280
+ return false;
281
+
282
+ // 特定のURLに該当する場合、CSRFチェックしない
283
+ if(matcher.matches(request))
284
+ return false;
285
+
286
+ return true;
287
+ }
288
+ }
289
+ ```
290
+
291
+ ```java
292
+ //上記のRequestMatcherを反映させたSecuriryConfigクラス
293
+
294
+ package com.example.demo;
295
+
296
+ import javax.sql.DataSource;
297
+
298
+ import org.springframework.beans.factory.annotation.Autowired;
299
+ import org.springframework.context.annotation.Bean;
300
+ import org.springframework.context.annotation.Configuration;
301
+ import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
302
+ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
303
+ import org.springframework.security.config.annotation.web.builders.WebSecurity;
304
+ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
305
+ import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
306
+ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
307
+ import org.springframework.security.crypto.password.PasswordEncoder;
308
+ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
309
+ import org.springframework.security.web.util.matcher.RequestMatcher;
310
+
311
+ @EnableWebSecurity
312
+ @Configuration
313
+ public class SecurityConfig extends WebSecurityConfigurerAdapter {
314
+
315
+ // データソース
316
+ @Autowired
317
+ private DataSource dataSource;
318
+
319
+ @Bean
320
+ public PasswordEncoder passwordEncoder() {
321
+ return new BCryptPasswordEncoder();
322
+ }
323
+
324
+ // ユーザーIDとパスワードを取得するSQL文
325
+ private static final String USER_SQL = "SELECT"
326
+ + " user_id,"
327
+ + " password,"
328
+ + " true"
329
+ + " FROM"
330
+ + " m_user"
331
+ + " WHERE"
332
+ + " user_id = ?";
333
+
334
+ // ユーザーのロールを取得するSQL文
335
+ private static final String ROLE_SQL = "SELECT"
336
+ + " user_id,"
337
+ + " role"
338
+ + " FROM"
339
+ + " m_user"
340
+ + " WHERE"
341
+ + " user_id = ?";
342
+
343
+ @Override
344
+ public void configure(WebSecurity web) throws Exception {
345
+
346
+ //静的リソースへのアクセスには、セキュリティを適用しない
347
+ web.ignoring().antMatchers("/webjars/∗∗", "/css/∗∗");
348
+ }
349
+
350
+ @Override
351
+ protected void configure(HttpSecurity http) throws Exception {
352
+
353
+ // ログイン不要ページの設定
354
+ http
355
+ .authorizeRequests()
356
+ .antMatchers("/webjars/**").permitAll() //webjarsへアクセス許可
357
+ .antMatchers("/css/**").permitAll() //cssへアクセス許可
358
+ .antMatchers("/login").permitAll() //ログインページは直リンクOK
359
+ .antMatchers("/signup").permitAll() //ユーザー登録画面は直リンクOK
360
+ .antMatchers("/rest/**").permitAll() //RESTは直リンクOK
361
+ .antMatchers("/admin").hasAuthority("ROLE_ADMIN") //アドミンユーザーに許可
362
+ .anyRequest().authenticated(); //それ以外は直リンク禁止
363
+
364
+ //ログイン処理
365
+ http
366
+ .formLogin()
367
+ .loginProcessingUrl("/login") //ログイン処理のパス
368
+ .loginPage("/login") //ログインページの指定
369
+ .failureUrl("/login") //ログイン失敗時の遷移先
370
+ .usernameParameter("userId") //ログインページのユーザーID
371
+ .passwordParameter("password") //ログインページのパスワード
372
+ .defaultSuccessUrl("/home", true); //ログイン成功後の遷移先
373
+
374
+ //ログアウト処理
375
+ http
376
+ .logout()
377
+ .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) //
378
+ .logoutUrl("/logout") //ログアウトのURL
379
+ .logoutSuccessUrl("/login"); //ログアウト成功後のURL
380
+
381
+ //CSRFを無効にするURLを設定
382
+ RequestMatcher csrfMatcher = new RestMatcher("/rest/**");
383
+
384
+ //RESTのみCSRF対策を無効に設定
385
+ http.csrf().requireCsrfProtectionMatcher(csrfMatcher);
386
+ }
387
+
388
+ @Override
389
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
390
+
391
+ // ログイン処理時のユーザー情報を、DBから取得する
392
+ auth.jdbcAuthentication()
393
+ .dataSource(dataSource)
394
+ .usersByUsernameQuery(USER_SQL)
395
+ .authoritiesByUsernameQuery(ROLE_SQL)
396
+ .passwordEncoder(passwordEncoder());
397
+ }
398
+ }
399
+
400
+ ```