Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- typescript 기초문법
- 괄호 회전하기 파이썬
- 타입스크립트 기초
- 스프링부트 미니프로젝트
- springboot 게시판
- 스프링부트 블로그
- springboot 게시판만들기
- JS기초
- 프로그래머스 괄호 회전하기 python
- springboot 사이드프로젝트
- 타입스크립트 기본문법
- jpa 게시판
- 유니티기초
- 스프링 게시판 만들기
- 유니티Cube
- 스프링부트 게시판만들기
- 유니티
- 스프링부트 회원가입
- 파이썬 괄호 회전하기
- 유니티Material
- python 괄호 회전하기
- spring jpa 게시판
- 스프링부트 update
- 타입스크립트 기초문법
- springboot 미니프로젝트
- 파이썬 기초
- spring jpa 사이드프로젝트
- springboot 게시판 프로젝트
- 스프링게시판프로젝트
- 스프링부트 블로그만들기
Archives
- Today
- Total
Digking's cave
My First Blog Project (12) : SpringSecurit 적용 및 로그인 페이지 생성 본문
Spring/My First Blog Project
My First Blog Project (12) : SpringSecurit 적용 및 로그인 페이지 생성
디깅 2022. 12. 19. 11:13728x90
# Spring Security 적용에 앞서 기존 코드 및 주소 정리
- / (컨텍스트 삭제)
- /auth/joinProc
- /auth/loginProc
- /auth/joinForm
- /auth/loginForm
header.jsp
joinForm.jsp
user.js
UserApiController.java
UserController.java
인증 안 된 사용자들이 출입할 수 있는 경로는 앞에 /auth 붙임 - /auth/** 허용
그냥 주소가 / 이면 index.jsp 허용
static 이하에 있는 /js/**, /css/**, /image/**
application.yml
server:
port: 8000
servlet:
context-path: /
encoding:
charset: UTF-8
enabled: true
force: true
UserController.java
package com.cos.blog.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
// 인증 안 된 사용자들이 출입할 수 있는 경로를 /auth/** 허용
// 그냥 주소가 / 이면 index.jsp 허용
// static 이하에 있는 /js/**, /css/**, /image/**
@Controller
public class UserController {
@GetMapping("/auth/joinForm")
public String joinForm(){
return "user/joinForm";
}
@GetMapping("/auth/loginForm")
public String loginForm(){
return "user/loginForm";
}
}
UserApiController.java
package com.cos.blog.controller.api;
import com.cos.blog.dto.ResponseDto;
import com.cos.blog.model.RoleType;
import com.cos.blog.model.User;
import com.cos.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
public class UserApiController {
@Autowired
private UserService userService;
@PostMapping("/auth/joinProc")
public ResponseDto<Integer> save(@RequestBody User user) {
user.setRoles(RoleType.USER);
userService.회원가입(user);
return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
}
}
UserReository.java
package com.cos.blog.repository;
import com.cos.blog.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User, Integer> {
}
UserService.java
package com.cos.blog.service;
import com.cos.blog.model.User;
import com.cos.blog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void 회원가입(User user){
userRepository.save(user);
}
}
header.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="isAuthenticated()">
<sec:authentication property="principal" var="principal"/>
</sec:authorize>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="/">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<c:choose>
<c:when test="${empty principal}">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/auth/loginForm">로그인</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/auth/joinForm">회원가입</a>
</li>
</ul>
</c:when>
<c:otherwise>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/board/form">글쓰기</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/user/form">회원정보</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout">로그아웃</a>
</li>
</ul>
</c:otherwise>
</c:choose>
</div>
</nav>
<br/>
joinForm.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="../layout/header.jsp" %>
<div class="container">
<form>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" placeholder="Enter Username" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" placeholder="Enter password" id="pwd">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" placeholder="Enter email" id="email">
</div>
</form>
<button id="btn-save" class="btn btn-primary">회원가입 완료</button>
</div>
<script src="/js/user.js"></script>
<%@ include file="../layout/footer.jsp" %>
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="../layout/header.jsp" %>
<div class="container">
<form action="#" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" name="username" class="form-control" placeholder="Enter Username" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" name="password" class="form-control" placeholder="Enter password" id="pwd">
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" name="remember" type="checkbox"> Remember me
</label>
</div>
<button id="btn-login" class="btn btn-primary">로그인</button>
</form>
</div>
<script src="/js/user.js"></script>
<%@ include file="../layout/footer.jsp" %>
user.js
let index = {
init: function(){
$("#btn-save").on("click",()=>{
this.save();
});
},
save:function(){
let data = {
username: $("#username").val(),
password: $("#pwd").val(),
email: $("#email").val()
};
$.ajax({
type:"POST",
url:"/auth/joinProc",
data: JSON.stringify(data), //http body 데이터
contentType: "application/json; charset=utf-8"
}).done(function(resp){
alert("회원가입 완료되었습니다.");
location.href = "/";
}).fail(function(error){
alert(JSON.stringify(error));
});
}
}
index.init();
config 패키지 생성
config/SecurityConfig.java
package com.cos.blog.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
@Configuration //빈등록 (IoC관리)
@EnableWebSecurity //security 필터 등록
@EnableGlobalMethodSecurity(prePostEnabled = true) //특정 주소를 접근을 하면 권한 및 인증을 미리 체크하겠다는 뜻
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/auth/loginForm");
return http.build();
}
}
반응형
'Spring > My First Blog Project' 카테고리의 다른 글
My First Blog Project (14) : SpringSecurity 로그인 구현 (0) | 2022.12.21 |
---|---|
My First Blog Project (13) : 비밀번호 해쉬화 회원가입 / 권한에 따른 페이지 처리 (0) | 2022.12.20 |
My First Blog Project (11) : 회원가입 / 로그인 처리 완료 (0) | 2022.12.18 |
My First Blog Project (10) : 블로그 메인 / 로그인 / 회원가입 화면 (0) | 2022.12.17 |
My First Blog Project (9) : Exception 처리 (0) | 2022.12.16 |