Study/Java
[Spring] spring boot security - login 만들기
momong'-'
2020. 7. 5. 20:35
pom.xml
1
2
3
4
5
|
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
|
cs |
Maven에 들어가서 spring boot security 검색하여 원하는 버젼 다운
http:s//mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
Maven Repository: org.springframework.boot » spring-boot-starter-security
Starter for using Spring Security VersionRepositoryUsagesDate2.3.x2.3.1.RELEASECentral22Jun, 20202.3.0.RELEASECentral46May, 20202.2.x2.2.8.RELEASECentral2Jun, 20202.2.7.RELEASECentral29May, 20202.2.6.RELEASECentral46Mar, 20202.2.5.RELEASECentral44Feb, 2020
mvnrepository.com
LoginController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package simple.login;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String indexWindow(Model model) {
return "login/login";
}
}
|
cs |
SpringSecurityConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package simple.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalAuthentication
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthProvider authProvider;
@Autowired
private LoginHandler loginHandler;
// 스프링 시큐리티의 필터 연결 설정
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
// 인터셉터로 요청을 안전하게 보호하는 방법 설정
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").permitAll().loginProcessingUrl("/login")
.usernameParameter("userId").passwordParameter("passwd")
.successHandler(loginHandler)
.failureHandler(loginHandler).permitAll()
.and()
.logout().logoutUrl("/logout").logoutSuccessHandler(loginHandler).invalidateHttpSession(true).permitAll();
}
// 사용자 세부 서비스 설정
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
}
|
cs |
Interface WebSecurityConfigurer<T extends SecurityBuilder<javax.servlet.Filter>>
WebSecurityConfigurerAdapter
=> Adapter는 implements한 인터페이스를 모두 오버라이드 한 클래스
=> 메소드를 부분만 사용할 수 있게 만들어 놓은 클래스임
=> Adapter를 extends하면 사용할 클래스만 extends하면 됨
AuthProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
package simple.configuration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.stereotype.Component;
import simple.user.UserService;
import simple.user.UserVo;
@Component
public class AuthProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userIdInput = authentication.getName();
String passwdInput = (String) authentication.getCredentials();
UsernamePasswordAuthenticationToken token;
UserVo userVo = userService.selectUserOne(new UserVo(userIdInput));
if ( userVo != null && userVo.getPasswd().equals(passwdInput) ) {
List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
roles.add(new SimpleGrantedAuthority("USER"));
token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), roles);
token.setDetails(userVo);
return token;
}
else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
|
cs |
LoginHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package simple.configuration;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import simple.user.UserVo;
@Component
public class LoginHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
UserVo userVo = (UserVo) authentication.getDetails();
request.getSession().setAttribute("userVo", new UserVo());
response.sendRedirect("/user/indexWindow");
System.out.println("로그인 성공");
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendRedirect("/login");
System.out.println("로그인 실패");
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
request.getSession().invalidate();
response.sendRedirect("/login");
}
}
|
cs |
login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
<link rel="stylesheet" href="/resources/lib/jqWidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="/resources/lib/jquery/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="/resources/lib/jqWidgets/jqx-all.js"></script>
<style>
body {
width: 100%;
height: 600px;
background: #fff;
margin: 0 auto;
display: table;
}
#loginContent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
#loginForm {
width: 400px;
display: inline-block;
}
</style>
<script type="text/javascript">
$(function() {
initComponent();
});
function initComponent() {
var template = [
{bind:'userId', name:'userId', type:'text', label:'아이디', required:true, labelWidth:'80px', width:'250px', height: '25px'}
, {bind:'passwd', name: 'passwd', type:'password', label:'비밀번호', required:true, labelWidth:'80px', width:'250px'}
];
$('#loginForm').jqxForm({
template: template,
padding: { left: 10, top: 10, right: 10, bottom: 10 }
});
$("#loginBtn").jqxButton({ width: '100', height: '25', value:'로그인'});
$("#loginBtn").on('click', function() {
$('#loginForm').jqxForm('submit', "/login", null, 'POST');
});
}
</script>
</head>
<body>
<div id="loginContent">
<div id="loginForm">
</div>
<div style="width: 100%; text-align: center;">
<div style="display: inline-block; text-align: center; margin-top:10px;">
<input type="button" id="loginBtn" />
</div>
</div>
</div>
</body>
</html>
|
cs |
실행결과