Category: Form login

0

Spring Security Form Login - 4. 회원가입 페이지 만들기

회원가입을 처리하기 위한 Controller 추가 요청으로 들어온 데이터를 받기 위한 DTO객체 생성 회원가입 page생성하기 회원 가입을 처리하기 위한 Controller 추가/signup으로 들어온 사용자 정보를 DTO객체로 받고 Account객체를 생성한 후 DB에 저장한다. @Controller@RequiredArgsConstructorpublic class SecurityController { private final CustomUserDetailsService customUserDetailsService; private final PasswordEncoder passwordEncoder; @GetMapping("/") public String index(){ return "index"; } @GetMapping("/login") public String login(){ return "login"; } @GetMapping("/logout") public void logout(){ } @GetMapping("/signup") public String signup(@ModelAttribute("signupDto") AccountDto accountDto, Model model){ return "signup"; } @PostMapping("/signup") public String createNewAccount(@ModelAttribute("signupDto") @Validated AccountDto accountDto, Model model){ Account account = Account.builder() .username(accountDto.getUsername()) .email(accountDto.getEmail()) .password(passwordEncoder.encode(accountDto.getPassword())) .role(Role.USER) .build(); customUserDetailsService.saveAccount(account); return "redirect:"; }} User정보를 받기위한 DTO만들기@Datapublic class AccountDto { private String username; private String email; private String password;} 회원가입 template 만들기<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Bootstrap Registration Page with Floating Labels</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="robots" content="noindex, nofollow"> <meta name="googlebot" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1"><!-- <link rel="stylesheet" type="text/css" href="/css/result-light.css">--> <script type="text/javascript" th:src="@{/js/dummy.js}"></script> <script type="text/javascript" th:src="@{/js/jquery.slim.min.js}"></script> <script type="text/javascript" th:src="@{/js/bootstrap.bundle.min.js}"></script> <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/> <link rel="stylesheet" th:href="@{/css/all.css}"/> <link rel="stylesheet" th:href="@{/css/style.css}"/> <link rel="stylesheet" type="text/css" th:href="@{/css/signup.css}"/> <script id="insert"></script></head><body><div class="container"> <div class="row"> <div class="col-lg-10 col-xl-9 mx-auto"> <div class="card card-signin flex-row my-5"> <div class="card-img-left d-none d-md-flex"> <!-- Background image for card set in CSS! --> </div> <div class="card-body"> <h5 class="card-title text-center">Register</h5> <form class="form-signin" th:object="${signupDto}" th:action="@{/signup}" th:method="post"> <div class="form-label-group"> <input th:field="*{username}" type="text" id="inputUserame" class="form-control" placeholder="Username" required autofocus> <label for="inputUserame">Username</label> </div> <div class="form-label-group"> <input th:field="*{email}" type="email" id="inputEmail" class="form-control" placeholder="Email address" required> <label for="inputEmail">Email address</label> </div> <hr> <div class="form-label-group"> <input th:field="*{password}" type="password" id="inputPassword" class="form-control" placeholder="Password" required> <label for="inputPassword">Password</label> </div> <div class="form-label-group"> <input type="password" id="inputConfirmPassword" class="form-control" placeholder="Password" required> <label for="inputConfirmPassword">Confirm password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Register</button> </form> </div> </div> </div> </div></div><script type="text/javascript">//<![CDATA[//]]></script><script> // tell the embed parent frame the height of the content if (window.parent && window.parent.parent) { window.parent.parent.postMessage(["resultsFrame", { height: document.body.getBoundingClientRect().height, slug: "1nu8g6e5" }], "*") } // always overwrite window.name, in case users try to set it manually window.name = "result"</script></body></html> Form에서 기입된 데이터 보내기

0

Spring Security Form Login - 3. 템플릿 만들기

Spring에서 제공하는 Thymeleaf템플릿 엔진을 이용해 로그인 페이지를 구현했다. Form Login Page<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <title>Bootstrap Login Page Card with Floating Labels</title> <script type="text/javascript" th:src="@{/js/dummy.js}"></script> <script type="text/javascript" th:src="@{/js/jquery.slim.min.js}"></script> <script type="text/javascript" th:src="@{/js/bootstrap.bundle.min.js}"></script> <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/> <link rel="stylesheet" th:href="@{/css/all.css}"/> <link rel="stylesheet" th:href="@{/css/style.css}"/></head><body><div th:class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Sign In</h5> <form class="form-signin" th:action="@{/login}" method="post"> <div class="form-label-group"> <input type="text" th:name="username" class="form-control" placeholder="Email address" required autofocus> <label th:for="username">Email address</label> </div> <div class="form-label-group"> <input type="password" th:name="password" class="form-control" placeholder="Password" required> <label th:for="password">Password</label> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Remember password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button> </form> </div> </div> </div> </div></div></body></html> Form 로그인을 처리하는 url로 post요청을 보낸다. <form class="form-signin" th:action="@{/login}" method="post"> username과 password를 받는 input태그에서 name속성에 username과 password를 확실히 기입해줘야 Security가 해당 데이터를 얻어올 수 있다. <input type="text" th:name="username" class="form-control" placeholder="Email address" required autofocus>...<input type="password" th:name="password" class="form-control" placeholder="Password" required> 로그인 후 진입 화면<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"><head> <meta charset="UTF-8"> <title>Title</title></head><body><h1>시작페이지</h1><form action="/logout" th:action="@{/logout}" th:method="post" sec:authorize="isAuthenticated()"> <button type="submit" value="logout">로그 아웃</button></form></body></html>

0

Spring Security Form Login - 2. Security 설정 및 UserDetailsService 정의하기

로그인 로그아웃을 처리를 위한 Controller 생성 Spring Security 설정하기 UserDetailsService 구현하기 로그인 로그아웃을 처리를 위한 Controller/login으로 사용자 로그인 요청을 처리하고 /logout으로 사용자 로그아웃 요청을 처리한다. @Controller@RequiredArgsConstructorpublic class SecurityController { private final CustomUserDetailsService customUserDetailsService; private final PasswordEncoder passwordEncoder; @GetMapping("/") public String index(){ return "index"; } @GetMapping("/login") public String login(){ return "login"; } @GetMapping("/logout") public void logout(){ }} Spring Security 설정하기Spring Security를 설정하고 싶으면 EnableWebSecurity어노테이션과 WebSecurityConfigurerAdapter 클래스를 상속해 method들을 overriding한다. configure(AuthenticationManagerBuilder auth) AuthenticationManager를 설정하기 위해 사용하는 method configure(WebSecurity web) 전역적인 security를 설정할 때 사용하는 method, 보통은 보안 예외처리에 사용한다. configure(HttpSecurity http) request 단위로 보안을 걸때 사용하는 method configure(HttpSecurity http)을 이용해 허가를 하는 경우에는 Spring Filter Chain을 거처야 하지만 configure(WebSecurity web)를 이용하면 Spring Filter Chain을 거치지 않는다. @EnableWebSecurity@RequiredArgsConstructorpublic class SecurityConfig extends WebSecurityConfigurerAdapter { private final CustomUserDetailsService customUserDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserDetailsService); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/css/**", "/js/**") .antMatchers("/favicon.ico", "/resources/**", "/error") ; } @Override protected void configure(HttpSecurity http) throws Exception { http. authorizeRequests() .anyRequest().authenticated(); http .formLogin() // Form Login을 이용한 인증 방식을 사용 .loginPage("/login") // Login Page로 redirect할 경로를 적어준다. .defaultSuccessUrl("/", true) // 로그인 성공후 이동할 경로 .permitAll() ; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}

0

Spring Security Form Login - 1. 기본적인 모델 정의하기

Spring properties 설정하기Spring Security에서 사용하는 기본적인 user정보를 등록한다. jpa를 사용하므로 관련 옵션도 추가해준다. application.ymlspring: security: user: name: user password: 1234 jpa: hibernate: ddl-auto: create-drop properties: hibernate: show_sql: true format_sql: true profiles: include: mysqllogging: level: org.springframework.security: DEBUG application-mysql.ymlspring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/{테이블명}?serverTimezone=UTC&characterEncoding=UTF-8 username: user_id password: user_password jpa: database: mysql database-platform: org.hibernate.dialect.MySQL5InnoDBDialect Entity 생성하기사용자 정보를 저장하기 위한 Account Entity를 만든다. @Entity@NoArgsConstructor@AllArgsConstructor@Getterpublic class Account { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idx; private String username; @Column(unique = true, nullable = false) private String email; private String password; @Enumerated(EnumType.STRING) private Role role; private String getRoleValue(){ return this.role.getValue(); } @Builder public Account(String username, String email, String password, Role role){ this.username = username; this.email = email; this.password = password; this.role = role; }}