SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 인증 및 권한부여

This commit is contained in:
kimyonghwa
2019-04-16 15:54:37 +09:00
parent a7e3feb3bf
commit 41e93d885c
17 changed files with 182 additions and 77 deletions

View File

@@ -1,7 +1,7 @@
package com.rest.api.advice;
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
import com.rest.api.advice.exception.CEmailSigninFailedException;
import com.rest.api.advice.exception.CInvalidJwtAuthenticationException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.model.response.CommonResult;
import com.rest.api.service.ResponseService;
@@ -9,6 +9,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -26,7 +27,6 @@ public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
e.printStackTrace();
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
}
@@ -36,18 +36,23 @@ public class ExceptionAdvice {
return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
}
@ExceptionHandler(CInvalidJwtAuthenticationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult invalidJwtToken(HttpServletRequest request, CInvalidJwtAuthenticationException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("invalidJwtToken.code")), getMessage("invalidJwtToken.msg"));
}
@ExceptionHandler(CEmailSigninFailedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult emailSigninFailed(HttpServletRequest request, CEmailSigninFailedException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("emailSigninFailed.code")), getMessage("emailSigninFailed.msg"));
}
@ExceptionHandler(CAuthenticationEntryPointException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public CommonResult authenticationEntryPointException(HttpServletRequest request, CAuthenticationEntryPointException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("entryPointException.code")), getMessage("entryPointException.msg"));
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public CommonResult AccessDeniedException(HttpServletRequest request, AccessDeniedException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
}
private String getMessage(String code) {
return getMessage(code, null);

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CAuthenticationEntryPointException extends RuntimeException {
public CAuthenticationEntryPointException(String msg, Throwable t) {
super(msg, t);
}
public CAuthenticationEntryPointException(String msg) {
super(msg);
}
public CAuthenticationEntryPointException() {
super();
}
}

View File

@@ -1,15 +0,0 @@
package com.rest.api.advice.exception;
public class CInvalidJwtAuthenticationException extends RuntimeException {
public CInvalidJwtAuthenticationException(String msg, Throwable t) {
super(msg, t);
}
public CInvalidJwtAuthenticationException(String msg) {
super(msg);
}
public CInvalidJwtAuthenticationException() {
super();
}
}

View File

@@ -0,0 +1,28 @@
package com.rest.api.config.security;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/accessdenied");
dispatcher.forward(request, response);
}
}

View File

@@ -0,0 +1,24 @@
package com.rest.api.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/entrypoint");
dispatcher.forward(request, response);
}
}

View File

@@ -1,4 +1,4 @@
package com.rest.api.filter;
package com.rest.api.config.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -11,16 +11,16 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JwtTokenFilter extends GenericFilterBean {
public class JwtAuthenticationFilter extends GenericFilterBean {
private JwtTokenProvider jwtTokenProvider;
// Jwt Provier 주입
public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
// Request로 들어오는 Jwt Token의 유효성을 검증하는 filter를 filterChain에 등록합니다.
// Request로 들어오는 Jwt Token의 유효성을 검증(jwtTokenProvider.validateToken)하는 filter를 filterChain에 등록합니다.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);

View File

@@ -1,11 +1,11 @@
package com.rest.api.filter;
package com.rest.api.config.security;
import com.rest.api.advice.exception.CInvalidJwtAuthenticationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
@@ -22,9 +22,10 @@ import java.util.List;
@Component
public class JwtTokenProvider { // JWT 토큰을 생성 검증 모듈
private String secretKey = "secret";
@Value("spring.jwt.secret")
private String secretKey;
private long tokenValidMilisecond = 1000L * 60 * 60; // 1hour
private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효
private final UserDetailsService userDetailsService;
@@ -34,8 +35,8 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
}
// Jwt 토큰 생성
public String createToken(String username, List<String> roles) {
Claims claims = Jwts.claims().setSubject(username);
public String createToken(String userPk, List<String> roles) {
Claims claims = Jwts.claims().setSubject(userPk);
claims.put("roles", roles);
Date now = new Date();
return Jwts.builder()
@@ -48,16 +49,16 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
// Jwt 토큰으로 인증 정보를 조회
public Authentication getAuthentication(String token) {
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUsername(token));
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
// Jwt 토큰에서 회원 이름(ID) 추출
public String getUsername(String token) {
// Jwt 토큰에서 회원 구별 정보 추출
public String getUserPk(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjb2Rlajk5QG5hdmVyLmNvbSIsInJvbGVzIjpbIlJPTEVfVVNFUiJdLCJpYXQiOjE1NTUzMTY1NzksImV4cCI6MTU1NTMyMDE3OX0.ftuRcpLZmMbKoxM3pQB5VA9As9Yamt10FN6Lbgu-pjVB3AGZDWfS9WRzGNbtZkKvSZH9swx3WgrHnONyrUoaqA"
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"
public String resolveToken(HttpServletRequest req) {
return req.getHeader("X-AUTH-TOKEN");
}
@@ -68,7 +69,7 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
return !claims.getBody().getExpiration().before(new Date());
} catch (Exception e) {
throw new CInvalidJwtAuthenticationException();
return false;
}
}
}

View File

@@ -1,7 +1,5 @@
package com.rest.api.config;
package com.rest.api.config.security;
import com.rest.api.filter.JwtTokenFilter;
import com.rest.api.filter.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -35,14 +33,19 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signup").permitAll() // 가입 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
.anyRequest().authenticated() // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.antMatchers("/*/users").hasRole("ADMIN")
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()
.addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
.and()
.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.and()
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
}
@Override // ignore swagger security config
public void configure(WebSecurity web) throws Exception {
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
"/swagger-ui.html", "/webjars/**", "/swagger/**");

View File

@@ -0,0 +1,25 @@
package com.rest.api.controller.exception;
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
import com.rest.api.model.response.CommonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/exception")
public class ExceptionController {
@GetMapping(value = "/entrypoint")
public CommonResult entrypointException() {
throw new CAuthenticationEntryPointException();
}
@GetMapping(value = "/accessdenied")
public CommonResult accessdeniedException() {
throw new AccessDeniedException("");
}
}

View File

@@ -2,7 +2,7 @@ package com.rest.api.controller.v1;
import com.rest.api.advice.exception.CEmailSigninFailedException;
import com.rest.api.entity.User;
import com.rest.api.filter.JwtTokenProvider;
import com.rest.api.config.security.JwtTokenProvider;
import com.rest.api.model.response.CommonResult;
import com.rest.api.model.response.SingleResult;
import com.rest.api.repo.UserJpaRepo;
@@ -39,7 +39,7 @@ public class SignController {
if (!passwordEncoder.matches(password, user.getPassword()))
throw new CEmailSigninFailedException();
return responseService.getSingleResult(jwtTokenProvider.createToken(user.getUsername(), user.getRoles()));
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
}
@ApiOperation(value = "가입", notes = "회원가입을 한다.")

View File

@@ -9,6 +9,8 @@ import com.rest.api.repo.UserJpaRepo;
import com.rest.api.service.ResponseService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
@Api(tags = {"2. User"})
@@ -31,14 +33,16 @@ public class UserController {
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = false, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
@GetMapping(value = "/user/{msrl}")
public SingleResult<User> findUserById(@ApiParam(value = "회원번호", required = true) @PathVariable int msrl,
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
@ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
@GetMapping(value = "/user")
public SingleResult<User> findUserById(@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String id = authentication.getName();
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
return responseService.getSingleResult(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new));
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
}
@ApiImplicitParams({
@@ -47,7 +51,7 @@ public class UserController {
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
@PutMapping(value = "/user")
public SingleResult<User> modify(
@ApiParam(value = "회원번호", required = true) @RequestParam int msrl,
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
User user = User.builder()
.msrl(msrl)
@@ -59,10 +63,10 @@ public class UserController {
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
@ApiOperation(value = "회원 삭제", notes = "회원번호(msrl)로 회원정보를 삭제한다")
@DeleteMapping(value = "/user/{msrl}")
public CommonResult delete(
@ApiParam(value = "회원번호", required = true) @PathVariable int msrl) {
@ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {
userJpaRepo.deleteById(msrl);
// 성공 결과 정보만 필요한경우 getSuccessResult()를 이용하여 결과를 출력한다.
return responseService.getSuccessResult();

View File

@@ -1,7 +1,10 @@
package com.rest.api.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@@ -12,17 +15,16 @@ import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Setter
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user")
@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
@Id // pk
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int msrl;
private long msrl;
@Column(nullable = false, unique = true, length = 30)
private String uid;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@@ -40,26 +42,31 @@ public class User implements UserDetails {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Override
public java.lang.String getUsername() {
public String getUsername() {
return this.uid;
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Override
public boolean isEnabled() {
return true;

View File

@@ -5,7 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserJpaRepo extends JpaRepository<User, Integer> {
public interface UserJpaRepo extends JpaRepository<User, Long> {
Optional<User> findByUid(String email);
}

View File

@@ -13,7 +13,7 @@ public class CustomUserDetailService implements UserDetailsService {
private final UserJpaRepo userJpaRepo;
public UserDetails loadUserByUsername(String username) {
return userJpaRepo.findByUid(username).orElseThrow(CUserNotFoundException::new);
public UserDetails loadUserByUsername(String userPk) {
return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
}
}

View File

@@ -13,3 +13,5 @@ spring:
messages:
basename: i18n/exception
encoding: UTF-8
jwt:
secret: govlepel@$&

View File

@@ -4,9 +4,12 @@ unKnown:
userNotFound:
code: "-1000"
msg: "This member not exist"
invalidJwtToken:
code: "-1001"
msg: "Authentication information is not valid."
emailSigninFailed:
code: "-1001"
msg: "Your account does not exist or your email or password is incorrect."
entryPointException:
code: "-1002"
msg: "You do not have permission to access this resource."
accessDenied:
code: "-1003"
msg: "A resource that can not be accessed with the privileges it has."

View File

@@ -4,9 +4,12 @@ unKnown:
userNotFound:
code: "-1000"
msg: "존재하지 않는 회원입니다."
invalidJwtToken:
code: "-1001"
msg: "인증 정보가 유효하지 않습니다."
emailSigninFailed:
code: "-1001"
msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."
entryPointException:
code: "-1002"
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
accessDenied:
code: "-1003"
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."