Skip to content
Permalink
Browse files

authentication

  • Loading branch information...
teachingprogramming committed Jul 3, 2018
1 parent 2d344eb commit 5af0a087c2e09d64c339f59717b2b2cc7cbb9e8d
@@ -30,4 +30,5 @@ dependencies {
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('com.h2database:h2')
compile('org.springframework.boot:spring-boot-starter-security')
}
@@ -0,0 +1,83 @@
package d00000.webapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;


/**
* 認証
*/
@Controller
@RequestMapping("/auth")
public class AuthController {

private JdbcUserDetailsManager jdbcUserDetailsManager;
private PasswordEncoder passwordEncoder;

/** コンストラクタ */
public AuthController(@Autowired JdbcUserDetailsManager jdbcUserDetailsManager, @Autowired PasswordEncoder passwordEncoder) {
this.jdbcUserDetailsManager = jdbcUserDetailsManager;
this.passwordEncoder = passwordEncoder;
}

/** DIが終わった後に実行されるメソッド */
@PostConstruct
private void postConstruct() {
if (!jdbcUserDetailsManager.userExists("user1")) {
String encodedPassword = "$2a$04$SwtM.7S/4egN/2mcxZn4DO5y4ZkKOoBqFmFvA4PFY98sVJOJxoRDS"; // 「password1」をBCryptでhash化したもの
UserDetails user1 = User.withUsername("user1").password(encodedPassword).roles("USER").build();
jdbcUserDetailsManager.createUser(user1);
}
}

/** トップページ */
@GetMapping("/")
public String index() {
return "auth/index";
}

/** ログインフォーム */
@GetMapping("/login")
public String login() {
return "auth/login";
}


/** 認証済みユーザのページ */
@GetMapping("/secret/")
public String secretIndex(@AuthenticationPrincipal UserDetails userDetails, ModelMap modelMap) {
modelMap.addAttribute("username", userDetails.getUsername());
return "auth/secret/index";
}

/** ユーザ追加フォーム */
@GetMapping("/add_user")
public String addUserGet() {
return "auth/add_user";
}

/** ユーザ追加処理 */
@PostMapping("/add_user")
public String addUserPost(@RequestParam("username") String username, @RequestParam("password") String password,
@RequestParam("role") String role) {
if (!jdbcUserDetailsManager.userExists(username)) {
String encodedPassword = this.passwordEncoder.encode(password);
UserDetails user = User.withUsername(username).password(encodedPassword).roles(role).build();
jdbcUserDetailsManager.createUser(user);
}
return "redirect:/auth/";
}

}
@@ -0,0 +1,41 @@
package d00000.webapp;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
// 「/auth/secret/**」は認証が必要で、それ以外は認証が不要
http.authorizeRequests().antMatchers("/auth/secret/**").authenticated().anyRequest().permitAll();

// ログイン
http.formLogin().loginPage("/auth/login").usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/auth/loginProcess").permitAll().defaultSuccessUrl("/auth/secret/").failureUrl("/auth/login?error");

// ログアウト
http.logout().logoutUrl("/auth/logout").logoutSuccessUrl("/auth/");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(DataSource dataSource) {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(dataSource);
return jdbcUserDetailsManager;
}

}
@@ -0,0 +1,10 @@
create table if not exists users (
username varchar(256),
password varchar(256),
enabled boolean
);

create table if not exists authorities (
username varchar(256),
authority varchar(256)
);
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>ユーザ追加</title>
</head>
<body>
<h1>ユーザ認証サンプル</h1>
<h2>ユーザ追加</h2>
<form th:action="@{/auth/add_user}" method="post">
ユーザ名: <input name="username"/><br/>
パスワード: <input name="password" type="password"/><br/>
ロール: <select name="role"><option value="USER">一般ユーザ</option><option value="ADMIN">管理者</option></select><br/>
<button type="submit">追加</button>
</form>
</body>
</html>
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>インデックス</title>
</head>
<body>
<h1>ユーザ認証サンプル</h1>
<h2>インデックス</h2>
<ul>
<li><a href="/auth/login">ログインフォーム</a></li>
<li><a href="/auth/secret/">認証済みユーザページ</a></li>
<li><a href="/auth/add_user">ユーザ追加</a></li>
</ul>
</body>
</html>
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>ログイン</title>
</head>
<body>
<h1>ユーザ認証サンプル</h1>
<h2>ログイン</h2>
<p th:if="${param.error}">
<strong style="color: red">ユーザ名またはパスワードが違います。</strong>
</p>
<form th:action="@{/auth/loginProcess}" method="post">
ユーザ名: <input name="username"/><br/>
パスワード: <input name="password" type="password"/><br/>
<button type="submit">ログイン</button>
</form>
</body>
</html>
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>認証済みユーザページ</title>
</head>
<body>
<h1>ユーザ認証サンプル</h1>
<h2>認証済みユーザページ</h2>
<p>
「<span th:text="${username}"></span> 」でログイン中です。
</p>
<p>
<form th:action="@{/auth/logout}" method="post">
<button type="submit">ログアウト</button>
</form>
</p>
</body>
</html>

0 comments on commit 5af0a08

Please sign in to comment.
You can’t perform that action at this time.