SecurityConfig
package com.demo.t1.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import com.demo.t1.auth.PrincipalDetailService;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private PrincipalDetailService principalDetailService;
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(principalDetailService).passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.antMatchers("/","/auth/**","/css/**","/js/**","/css/**","/image/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/auth/login_form")
.loginProcessingUrl("/auth/loginProc")
.defaultSuccessUrl("/");
}
}
login_form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container">
<form action="/auth/loginProc" method="post">
<div class="form-group">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
<label for="username">username:</label> <input type="text" class="form-control" placeholder="Enter usernmae" id="username" name="username"
value="teco">
</div>
<div class="form-group">
<label for="password">password:</label> <input type="password" class="form-control" placeholder="Enter password" id="password" name="password"
value="asd123">
<button type="submit" id="btn--login" class="btn btn-primary">signIn</button>
</div>
</form>
</div>
<%@ include file="../layout/footer.jsp"%>
PrincipalDetail
package com.demo.t1.auth;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.demo.t1.dto.User;
public class PrincipalDetail implements UserDetails{
private User user;
public PrincipalDetail(User user) {
this.user = user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> collection = new ArrayList<GrantedAuthority>();
collection.add(() -> {
return "ROLE_" + user.getRole();
});
return collection;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return user.getPassword();
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
PrincipalDetailService
package com.demo.t1.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.demo.t1.dto.User;
import com.demo.t1.repository.UserRepository;
@Service
public class PrincipalDetailService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User principal = userRepository.findByUsername(username).orElseThrow(() -> {
return new UsernameNotFoundException("해당유저를 찾을수 없습니다.");
});
return new PrincipalDetail(principal);
}
}
header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ 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>
<head>
<meta charset="UTF-8">
<meta id="_csrf" name="${_csrf.parameterName}" content="${_csrf.token}">
<meta id="_csrf_header" name="_csrf_header" content="${_csrf.headerName}">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.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.1/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">
<ul class="navbar-nav">
<c:choose>
<c:when test="${empty principal}">
<li class="nav-item"><a class="nav-link" href="/auth/login_form">로그인</a></li>
<li class="nav-item"><a class="nav-link" href="/auth/join_form">회원가입</a></li>
</c:when>
<c:otherwise>
<li class="nav-item"><a class="nav-link" href="/board/save_form">글쓰기</a></li>
<li class="nav-item"><a class="nav-link" href="/user/update_form">회원정보</a></li>
<li class="nav-item"><a class="nav-link" href="/m-logout">로그아웃</a></li>
</c:otherwise>
</c:choose>
</ul>
</div>
</nav>
<br>
'개발일지 > 스프링' 카테고리의 다른 글
Spring AOP (개념, 용어, 원리, 포인트컷 표현식, JoinPoint API) (0) | 2024.03.03 |
---|---|
아이디, 비밀번호 찾기 기능 (0) | 2023.01.08 |
spring boot 회원가입 기능 (0) | 2022.12.20 |
csrf적용한 로그인(아웃), 회원가입,댓글(작,삭),게시글(작,수,삭),회원정보(수정) (1) | 2022.12.20 |
spring boot 댓글 삭제기능 (0) | 2022.12.19 |
댓글