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

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

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

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

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Q&A

解決済

1回答

6734閲覧

SpringSecurityのログイン画面について

heavyuseman

総合スコア42

Java

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

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

0グッド

1クリップ

投稿2017/05/31 06:00

編集2017/06/04 06:10

いつもお世話になっております。
SpringSecurityのログイン画面を作成しております。
内容としましては、MysqlのNewaccountテーブルに登録しているユーザを
検索するものです。
名前とパスワードを入力し実行したのですが、下記のエラーが発生しました。

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed May 31 14:54:11 JST 2017
There was an unexpected error (type=Not Found, status=404).
No message available
原因が不明ですのでご回答宜しくお願い致します
-20170605追記
SecurityConfig.javaの箇所でブレークポイントし、デバックしたところ
Source not foundeエラーが出ました。
内容としましては
Spring-security-config-4-2-1RELEASE.jarファイルが
no source attachment
と出てきました。
gradleでSpring-security-config-4-2-1RELEASE.jarファイルを
入れるように設定しているため、設定しているはずなのですが
エラーが出てくるのが何故なのか不明です。
原因が不明ですのでご回答宜しくお願い致します

java

1//Datasource.java 2package com.tuyano.springboot.springsecurity; 3 4import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; 5import javax.sql.DataSource; 6import org.apache.commons.dbcp.BasicDataSource; 7import org.springframework.beans.factory.annotation.Value; 8import org.springframework.context.annotation.Bean; 9import org.springframework.context.annotation.Configuration; 10import org.springframework.context.annotation.PropertySource; 11import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 12import org.springframework.core.io.ClassPathResource; 13import org.springframework.core.io.FileSystemResource; 14import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; 15@Configuration 16@PropertySource("application.properties") 17public class DataSourceConfig { 18 19 @Value("${spring.datasource.driverClassName}") 20 private String driverClassName; 21 @Value("${spring.datasource.url}") 22 private String url; 23 @Value("${spring.datasource.username}") 24 private String userName; 25 @Value("${spring.datasource.password}") 26 private String password; 27 28 @Bean 29 public static PropertySourcesPlaceholderConfigurer propertyConfig() { 30 return new PropertySourcesPlaceholderConfigurer(); 31 } 32 @Bean(destroyMethod="close") 33 public DataSource dataSource() { 34 35 BasicDataSource ds = new BasicDataSource() { 36 @Override 37 public String toString() { 38 return "[driverClassName=" + driverClassName + ",username=" + userName + ", password=" + password+ "]"; 39 } 40 }; 41 ds.setDriverClassName(driverClassName); 42 ds.setUrl(url); 43 ds.setUsername(userName); 44 ds.setPassword(password); 45 System.out.println("dsの値"+ds); 46 return ds; 47 48 }

HTML

1//First.html 2<!DOCTYPE html> 3<html xmlns:th="http://www.thymeleaf.org"> 4<head> 5<title>top page</title> 6<meta http-equiv="Content-Type" 7content="text/html" charset="UTF-8"/> 8</head> 9<body> 10<form action="/processLogin" > 11 <dl> 12 <dt> 13 ログイン名前 14 </dt> 15 <dd> 16 <input type="text" name="name"></input> 17</dd> 18 <dt> 19 ログインパスワード 20 </dt> 21 <dd> 22 <input type="password" name="password"></input> 23 </dd> 24 </dl> 25 <button>ログイン</button> 26</form> 27 <hr/> 28 <form action="urlForUpload" enctype="multipart/form-data" method="post"> 29 <div class="form-group"> 30 <label>■ファイル種類:</label> 31 <select id="select_file_type" name="select_file_type" required=""> 32 <option value="login-user">ログインユーザー</option> 33 <!-- アップロードするファイルを定義していく --> 34 </select> 35 </div> 36 <div class="form-group"> 37 <label>■ファイルパス:</label> 38 <input type="file" id="upload_file" name="upload_file" required="" /> 39 </div> 40 <div class="form-group"> 41 <input id="data_upload_button" type="submit" value="アップロード" /> 42 </div> 43 </form> 44 <table> 45<tr><th>名前</th><th>住所</th></tr> 46<tr th:each="obj :${datalist}"> 47<td th:text="${obj.name}"></td> 48 49</tr> 50</table> 51 <div id ="map"></div> 52<script type="text/javascript" src="js/main.js" 53 54</body> 55 56</html>

java

1//Security.config 2package com.tuyano.springboot.springsecurity; 3 4import org.springframework.context.annotation.Bean; 5import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 6import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 11import javax.sql.DataSource; 12 13import org.springframework.beans.factory.annotation.Autowired; 14import org.springframework.beans.factory.annotation.Qualifier; 15 16 17 18@EnableWebSecurity 19public class SecurityConfig extends WebSecurityConfigurerAdapter{ 20 @Autowired 21 private DataSource dataSource; 22 23 private static final String USER_QUERY="select name, password, 1 from Newaccount where name = ?"; 24 private static final String ROLES_QUERY="select username, authority from AUTHORITIES where username = ?"; 25 26 @Override 27 protected void configure(HttpSecurity http) throws Exception{ 28 http 29 .authorizeRequests() 30 .antMatchers("/First.html").permitAll() 31 .antMatchers("/templates/**").hasAnyAuthority("ROLE_ADMIN") 32 .anyRequest().authenticated() 33 .and() 34 .formLogin() 35 .loginPage("/First.html") 36 .loginProcessingUrl("/processLogin") 37 .defaultSuccessUrl("/sucess.html") 38 .failureUrl("/faliure.html") 39 .usernameParameter("name") 40 .passwordParameter("password") 41 .and() 42 .csrf() 43 .disable(); 44 45 } 46 @Override 47 public void configure(AuthenticationManagerBuilder auth) throws Exception { 48 auth.jdbcAuthentication() 49 .dataSource(dataSource) 50 .usersByUsernameQuery(USER_QUERY) 51 .authoritiesByUsernameQuery(ROLES_QUERY); 52 //passwordEncoder(new BCryptPasswordEncoder()); 53 //.authoritiesByUsernameQuery( 54 // "select mail_address, role from accounts where mail_address = ?"); 55 } 56 57 58}

gradle

1buildscript { 2 ext { 3 springBootVersion = '1.5.1.RELEASE' 4 } 5 repositories { 6 mavenCentral() 7 } 8 dependencies { 9 classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 } 11} 12 13apply plugin: 'java' 14apply plugin: 'eclipse-wtp' 15apply plugin: 'org.springframework.boot' 16apply plugin: 'war' 17 18war { 19 baseName = 'MybootApp' 20 version = '0.0.1-SNAPSHOT' 21} 22 23sourceCompatibility = 1.8 24 25repositories { 26 mavenCentral() 27} 28 29configurations { 30 providedRuntime 31} 32 33dependencies { 34 //SpringSecurityを使うため、追加 35 compile('org.springframework.boot:spring-boot-starter-security') 36 compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4') 37 compile('org.springframework.boot:spring-boot-starter-data-jpa') 38 compile('org.springframework.boot:spring-boot-starter-thymeleaf') 39 compile('org.springframework.boot:spring-boot-starter-web') 40 runtime('mysql:mysql-connector-java') 41 providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') 42 testCompile('org.springframework.boot:spring-boot-starter-test') 43 // MySQL 44 //compile ("mysql:mysql-connector-java:$mySQLVersion") 45 //追記したMysqlのデータソース用 46 compile ('mysql:mysql-connector-java') 47 compile ('com.fasterxml.jackson.core:jackson-databind:2.8.8') 48 compile("org.springframework.boot:spring-boot-starter-thymeleaf") 49 compile 'commons-dbcp:commons-dbcp:1.4' 50 51} 52

NewaccountのDB(認証用DB)
イメージ説明

AUTHORITIESのDB(認可用DB)
![イメージ説明

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

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

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

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

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

guest

回答1

0

ベストアンサー

いくつか必要な設定が書かれてないので、すでに適用済みかも知れませんが、その場合ご容赦ください。

1 ユーザー認証のSQLが通りませんので、以下に修正してください。

java

1private static final String USER_QUERY 2 = "select name, password, 1 from Newaccount where name = ?";

2 アクセス制御ロールを取得するSQLが定義されていませんので、SpringSecurityは以下のSQLで自動的に発行されます。

SQL

1select username, authority from authorities where username = ?

これを参照するテーブル定義ならびにデータが登録されていないと、認証機能がエラーになります。

3 SpringSecirityConfigの認証部分の設定で、パスワードの項目がBCrypt設定されています。パスワードをハッシュ化した値を使っていないのであれば解除すべきでしょう。

@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery(USER_QUERY) .passwordEncoder(new BCryptPasswordEncoder()); // BCryptパスワードハッシュ } }

4 ログイン成功・失敗時のURL

ログイン成功・失敗URLでHTMLを指定していますが、HTMLを指定すると静的HTMLになりますので、springbootをお使いの場合は、src/main/resources/static に配置されているHTMLが呼び出されます。

ログイン成功・失敗時の動作が正しく動いているかどうかを確認するために、次のように修正し、src/main/resources/static 以下に それぞれのHTMLを置くと良いでしょう。

java

1 .defaultSuccessUrl("/success.html") 2 .failureUrl("/failure.html") 3

あと余談ですが、Controllerにて、ModelAndViewを引数に指定していますが、メソッド内で特に利用していないので、不要です。

java

1public ModelAndView NewAccountPost(@ModelAttribute("formModel") Newaccount newaccount,ModelAndView mav){

他にもライブラリ依存関係を変更されているようですが、その設定が書かれていないため、ソースが参照できるかどうかの判断はしかねます。

以下は動作確認のために適用したmaven設定です。参考までに。

xml

1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>com.example</groupId> 7 <artifactId>spring-security-sample</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging>jar</packaging> 10 11 <name>spring-security-sample</name> 12 <description>Demo project for Spring Boot</description> 13 14 <parent> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-parent</artifactId> 17 <version>1.5.3.RELEASE</version> 18 <relativePath/> <!-- lookup parent from repository --> 19 </parent> 20 21 <properties> 22 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 23 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 24 <java.version>1.8</java.version> 25 </properties> 26 27 <dependencies> 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-thymeleaf</artifactId> 31 </dependency> 32 33 <dependency> 34 <groupId>org.projectlombok</groupId> 35 <artifactId>lombok</artifactId> 36 <optional>true</optional> 37 </dependency> 38 <dependency> 39 <groupId>org.springframework.boot</groupId> 40 <artifactId>spring-boot-starter-test</artifactId> 41 <scope>test</scope> 42 </dependency> 43 <dependency> 44 <groupId>org.springframework.boot</groupId> 45 <artifactId>spring-boot-starter-security</artifactId> 46 </dependency> 47 <dependency> 48 <groupId>org.springframework.boot</groupId> 49 <artifactId>spring-boot-starter-web</artifactId> 50 </dependency> 51 <dependency> 52 <groupId>org.springframework.boot</groupId> 53 <artifactId>spring-boot-starter-jdbc</artifactId> 54 </dependency> 55 <dependency> 56 <groupId>org.apache.commons</groupId> 57 <artifactId>commons-dbcp2</artifactId> 58 </dependency> 59 <dependency> 60 <groupId>org.mariadb.jdbc</groupId> 61 <artifactId>mariadb-java-client</artifactId> 62 </dependency> 63 <dependency> 64 <groupId>org.springframework.boot</groupId> 65 <artifactId>spring-boot-devtools</artifactId> 66 </dependency> 67 </dependencies> 68 69 <build> 70 <plugins> 71 <plugin> 72 <groupId>org.springframework.boot</groupId> 73 <artifactId>spring-boot-maven-plugin</artifactId> 74 </plugin> 75 </plugins> 76 </build> 77</project>

参考資料:
http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/#jc-authentication-jdbc

投稿2017/05/31 06:43

編集2017/06/03 06:16
A-pZ

総合スコア12011

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

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

heavyuseman

2017/05/31 09:28 編集

ご回答ありがとうございます。 1 と from の間と、Newaccountとwheheの間に半角スペースを入れましょう。 上記のように対応したのですが、変わらず404エラーが発生してしまいました。
heavyuseman

2017/06/04 06:21

いつもご回答ありがとうございます。詳細に説明していただきまして誠にありがとうございます。 2 アクセス制御ロールを取得するSQLが定義されていませんので、SpringSecurityは以下のSQLで自動的に発行されます。 →2に対応するため、認可用のDBを作成し、またSecurity.config.javaも認可用に対応するように修正しました。 First.htmlのページからDBに登録しているユーザのログイン名、ログインパスワードを入力しログインしたところ,再度First.htmlのページが開きうまくログイン後の画面であるsucess.htmlに遷移しません。 デバックしたところ、質問欄に記載してあります 20170605追記 のエラーが出てきました。 エラー原因が不明ですのでご回答宜しくお願い致します。 DBの情報のキャプチャーとSecurity.configの編集、gradleのソースを追記しました。
A-pZ

2017/06/04 13:01

Spring-boot-starterのバージョンが1.5.1とのことで、念のため1.5.1にして動作確認しましたが、特に問題はありませんでした。 ですが他にも1点、やらなければならないことがありましたので追記します。 <form action="/processLogin" > にて、method="POST" が抜けております。GETメソッドではform認証はできませんので、必ずmethod="POST"を記載しましょう。 なお、ログインページを表示するために、ブラウザから次のURLでアクセスして検証しております。 http://127.0.0.1:8080/First.html
heavyuseman

2017/06/04 14:28

ご回答ありがとうございます。 form action="/processLogin" > にて、method="POST" が抜けております。GETメソッドではform認証はできませんので、必ずmethod="POST"を記載しましょう。 →上記を対応したところ、無事ログインができsucess.htmlに画面遷移できるようになりました。 お忙しい中ご対応していただきありがとうございました
A-pZ

2017/06/04 16:05

d(・ω・
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.51%

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

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

質問する

関連した質問