401 Unauthorized 해결을 위한 Security 설정
- 기본적인 Security 설정을 위한 SecurityConfig 클래스 생성
// main/java/me/gagyeong/tutorial/config/SecurityConfig.java
@EnableWebSecurity // 기본적인 web 보안 활성을 위한 어노테이션
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override // WebSecurityConfigurerAdapter의 configure 메소드를 오버라이드
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // HttpServletRequest를 사용하는 요청들에 대한 접근제한을 설정
.antMatchers("/api/hello").permitAll() // api/hello에 대한 요청은 인증없이 접근을 허용
.anyRequest().authenticated(); // 나머지 요청들은 모두 인증되어야 함
}
}
- Postman을 이용해 테스트 경우 401 에러가 발생하지 않음
hello 문자열이 응답 - 참고) [Spring Boot] 05장. 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기 - 구글 로그인 연동하기
Datasource, JPA 설정
- application.properties 파일을 application.yml 파일로 변경
h2 DB를 사용할 것이며, 메모리에 데이터를 저장할 거라는 설정을 작성했으며
Datasource 설정과 JPA 설정을 추가
JPA의 create-drop는 SessionFactory가 시작될 때 테이블을 Drop, Create, Alter하고 종료될 때 Drop을 진행하기 위해 사용
콘솔창에서 실행되는 sql들을 보기 좋게 보여주기 위해 format_sql, show_sql 설정을 추가
로깅 레벨도 디버그로 설정
// main/resources/application.yml
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
show_sql: true
logging:
level:
me.gagyeong: DEBUG
Entity 생성
- User, Authority 클래스 생성
// main/java/me/gagyeong/tutorial/entity/User.java
@Entity // 데이터베이스 테이블과 1:1 매핑되는 객체를 위한 어노테이션
@Table(name = "user") // 테이블명을 user로 지정
@Getter // 롬복 어노테이션 - Get 관련 코드 자동 생성
@Setter // 롬복 어노테이션 - Set 관련 코드 자동 생성
@Builder // 롬복 어노테이션 - Builder 관련 코드 자동 생성
@AllArgsConstructor // 롬복 어노테이션 - Constructor 관련 코드 자동 생성
@NoArgsConstructor // 롬복 어노테이션 - Constructor 관련 코드 자동 생성
public class User {
@JsonIgnore
@Id
@Column(name = "user_id") // 자동 증가되는 pk (primary key)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(name = "username", length = 50, unique = true) // username
private String username;
@JsonIgnore
@Column(name = "password", length = 100) // password
private String password;
@Column(name = "nickname", length = 50) // nickname
private String nickname;
@JsonIgnore
@Column(name = "activated") // 활성화 여부
private boolean activated;
// 권한들에 대한 관계
@ManyToMany // User 객체와 권한 객체의 테이블의 다대다 관계를
@JoinTable( // 일대다, 다대일 관계의 조인 테이블로 정의
name = "user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "authority_name")})
private Set<Authority> authorities;
}

// main/java/me/gagyeong/tutorial/entity/Authority.java
@Entity
@Table(name = "authority")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Authority {
@Id
@Column(name = "authority_name", length = 50) // 권한명이라는 pk
private String authorityName;
}
- create-drop 설정으로 인해 SpringBoot 서버가 시작될 때마다 테이블을 새로 만들기 때문에
편의를 위해서 서버를 시작할 때마다 Data를 자동으로 DB에 넣어주는 기능을 활용하여
서버가 시작될 때마다 실행할 쿼리문을 붙여넣기하면 이후 부터는 data.sql 쿼리들이 자동실행
// main/resources/data.sql
INSERT INTO USER (USER_ID, USERNAME, PASSWORD, NICKNAME, ACTIVATED) VALUES (1, 'admin', '$2a$08$lDnHPz7eUkSi6ao14Twuau08mzhWrL4kyZGGU5xfiGALO/Vxd5DOi', 'admin', 1);
INSERT INTO AUTHORITY (AUTHORITY_NAME) values ('ROLE_USER');
INSERT INTO AUTHORITY (AUTHORITY_NAME) values ('ROLE_ADMIN');
INSERT INTO USER_AUTHORITY (USER_ID, AUTHORITY_NAME) values (1, 'ROLE_USER');
INSERT INTO USER_AUTHORITY (USER_ID, AUTHORITY_NAME) values (1, 'ROLE_ADMIN');
- 우리가 만들었던 Entity들이 실제로 DB에 생성이 되는지 확인하기 위해 h2-console을 이용하기 위해 Security 설정을 추가
// main/java/me/gagyeong/tutorial/config/SecurityConfig.java
@EnableWebSecurity // 기본적인 web 보안 활성을 위한 어노테이션
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers(
"/h2-console/**" // h2-console 하위 모든 요청들과
,"/favicon.ico" // 파비콘 관련 요청은 Spring Security 로직을 수행하지 않도록 configure 메소드를 오버라이드
);
}
@Override // WebSecurityConfigurerAdapter의 configure 메소드를 오버라이드
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // HttpServletRequest를 사용하는 요청들에 대한 접근제한을 설정
.antMatchers("/api/hello").permitAll() // api/hello에 대한 요청은 인증없이 접근을 허용
.anyRequest().authenticated(); // 나머지 요청들은 모두 인증되어야 함
}
}
- 서버 시작 후, 콘솔을 보게 되면 우리가 만든 엔티티 내용들을 기반으로 DB에 관련 정보들을 생성하는 쿼리들이 수행된 것 확인
- Table "USER" not found 에러가 발생할 경우, application.yml에 추가 설정 필요
강의(2.4)에서와 내가 사용하는 스프링부트 버전(2.6)이 달라 생긴 문제
스프링부트 2.5버전부터 data.sql은 hibernate가 초기화되기 전에 실행되므로
hibernate가 초기화된 후 data.sql을 실행시키기 위해서는 application.yml에 추가 설정
// main/resources/application.yml
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
show_sql: true
defer-datasource-initialization: true
logging:
level:
me.gagyeong: DEBUG
- 브라우저를 통해 실제 DB를 확인
localhost:8080/h2-console 우리가 만들었던 Entity 정보들과 data.sql의 쿼리내용이 들어와 있는 것을 확인 가능
참고 영상 및 사이트
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-jwt/dashboard
[무료] Spring Boot JWT Tutorial - 인프런 | 강의
Spring Boot, Spring Security, JWT를 이용한 튜토리얼을 통해 인증과 인가에 대한 기초 지식을 쉽고 빠르게 학습할 수 있습니다., [사진] 본 강의는 Spring Boot, Spring Security를 이용해서 JWT 인증과 인가를 쉽
www.inflearn.com
Table "USER" not found 에러
[SpringBoot] 스프링부트 로그인 구현- (2) Security 설정, Data 설정
401 unauthorized 해결을 위한 Security 설정 / Datasource, JPA 설정 / Entity 생성 / H2 콘솔 결과 확인
velog.io
'Java-Spring > Spring Boot JWT Tutorial' 카테고리의 다른 글
Spring Boot JWT Tutorial - 목차 (0) | 2023.07.03 |
---|---|
[Spring Boot JWT Tutorial] 회원가입, 권한검증 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] DTO, Repository, 로그인 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] JWT 코드, Security 설정 추가 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] JWT 소개, 프로젝트 생성 (0) | 2022.01.22 |
401 Unauthorized 해결을 위한 Security 설정
- 기본적인 Security 설정을 위한 SecurityConfig 클래스 생성
// main/java/me/gagyeong/tutorial/config/SecurityConfig.java
@EnableWebSecurity // 기본적인 web 보안 활성을 위한 어노테이션
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override // WebSecurityConfigurerAdapter의 configure 메소드를 오버라이드
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // HttpServletRequest를 사용하는 요청들에 대한 접근제한을 설정
.antMatchers("/api/hello").permitAll() // api/hello에 대한 요청은 인증없이 접근을 허용
.anyRequest().authenticated(); // 나머지 요청들은 모두 인증되어야 함
}
}
- Postman을 이용해 테스트 경우 401 에러가 발생하지 않음
hello 문자열이 응답 - 참고) [Spring Boot] 05장. 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기 - 구글 로그인 연동하기
Datasource, JPA 설정
- application.properties 파일을 application.yml 파일로 변경
h2 DB를 사용할 것이며, 메모리에 데이터를 저장할 거라는 설정을 작성했으며
Datasource 설정과 JPA 설정을 추가
JPA의 create-drop는 SessionFactory가 시작될 때 테이블을 Drop, Create, Alter하고 종료될 때 Drop을 진행하기 위해 사용
콘솔창에서 실행되는 sql들을 보기 좋게 보여주기 위해 format_sql, show_sql 설정을 추가
로깅 레벨도 디버그로 설정
// main/resources/application.yml
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
show_sql: true
logging:
level:
me.gagyeong: DEBUG
Entity 생성
- User, Authority 클래스 생성
// main/java/me/gagyeong/tutorial/entity/User.java
@Entity // 데이터베이스 테이블과 1:1 매핑되는 객체를 위한 어노테이션
@Table(name = "user") // 테이블명을 user로 지정
@Getter // 롬복 어노테이션 - Get 관련 코드 자동 생성
@Setter // 롬복 어노테이션 - Set 관련 코드 자동 생성
@Builder // 롬복 어노테이션 - Builder 관련 코드 자동 생성
@AllArgsConstructor // 롬복 어노테이션 - Constructor 관련 코드 자동 생성
@NoArgsConstructor // 롬복 어노테이션 - Constructor 관련 코드 자동 생성
public class User {
@JsonIgnore
@Id
@Column(name = "user_id") // 자동 증가되는 pk (primary key)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(name = "username", length = 50, unique = true) // username
private String username;
@JsonIgnore
@Column(name = "password", length = 100) // password
private String password;
@Column(name = "nickname", length = 50) // nickname
private String nickname;
@JsonIgnore
@Column(name = "activated") // 활성화 여부
private boolean activated;
// 권한들에 대한 관계
@ManyToMany // User 객체와 권한 객체의 테이블의 다대다 관계를
@JoinTable( // 일대다, 다대일 관계의 조인 테이블로 정의
name = "user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "authority_name")})
private Set<Authority> authorities;
}

// main/java/me/gagyeong/tutorial/entity/Authority.java
@Entity
@Table(name = "authority")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Authority {
@Id
@Column(name = "authority_name", length = 50) // 권한명이라는 pk
private String authorityName;
}
- create-drop 설정으로 인해 SpringBoot 서버가 시작될 때마다 테이블을 새로 만들기 때문에
편의를 위해서 서버를 시작할 때마다 Data를 자동으로 DB에 넣어주는 기능을 활용하여
서버가 시작될 때마다 실행할 쿼리문을 붙여넣기하면 이후 부터는 data.sql 쿼리들이 자동실행
// main/resources/data.sql
INSERT INTO USER (USER_ID, USERNAME, PASSWORD, NICKNAME, ACTIVATED) VALUES (1, 'admin', '$2a$08$lDnHPz7eUkSi6ao14Twuau08mzhWrL4kyZGGU5xfiGALO/Vxd5DOi', 'admin', 1);
INSERT INTO AUTHORITY (AUTHORITY_NAME) values ('ROLE_USER');
INSERT INTO AUTHORITY (AUTHORITY_NAME) values ('ROLE_ADMIN');
INSERT INTO USER_AUTHORITY (USER_ID, AUTHORITY_NAME) values (1, 'ROLE_USER');
INSERT INTO USER_AUTHORITY (USER_ID, AUTHORITY_NAME) values (1, 'ROLE_ADMIN');
- 우리가 만들었던 Entity들이 실제로 DB에 생성이 되는지 확인하기 위해 h2-console을 이용하기 위해 Security 설정을 추가
// main/java/me/gagyeong/tutorial/config/SecurityConfig.java
@EnableWebSecurity // 기본적인 web 보안 활성을 위한 어노테이션
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers(
"/h2-console/**" // h2-console 하위 모든 요청들과
,"/favicon.ico" // 파비콘 관련 요청은 Spring Security 로직을 수행하지 않도록 configure 메소드를 오버라이드
);
}
@Override // WebSecurityConfigurerAdapter의 configure 메소드를 오버라이드
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // HttpServletRequest를 사용하는 요청들에 대한 접근제한을 설정
.antMatchers("/api/hello").permitAll() // api/hello에 대한 요청은 인증없이 접근을 허용
.anyRequest().authenticated(); // 나머지 요청들은 모두 인증되어야 함
}
}
- 서버 시작 후, 콘솔을 보게 되면 우리가 만든 엔티티 내용들을 기반으로 DB에 관련 정보들을 생성하는 쿼리들이 수행된 것 확인
- Table "USER" not found 에러가 발생할 경우, application.yml에 추가 설정 필요
강의(2.4)에서와 내가 사용하는 스프링부트 버전(2.6)이 달라 생긴 문제
스프링부트 2.5버전부터 data.sql은 hibernate가 초기화되기 전에 실행되므로
hibernate가 초기화된 후 data.sql을 실행시키기 위해서는 application.yml에 추가 설정
// main/resources/application.yml
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
show_sql: true
defer-datasource-initialization: true
logging:
level:
me.gagyeong: DEBUG
- 브라우저를 통해 실제 DB를 확인
localhost:8080/h2-console 우리가 만들었던 Entity 정보들과 data.sql의 쿼리내용이 들어와 있는 것을 확인 가능
참고 영상 및 사이트
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-jwt/dashboard
[무료] Spring Boot JWT Tutorial - 인프런 | 강의
Spring Boot, Spring Security, JWT를 이용한 튜토리얼을 통해 인증과 인가에 대한 기초 지식을 쉽고 빠르게 학습할 수 있습니다., [사진] 본 강의는 Spring Boot, Spring Security를 이용해서 JWT 인증과 인가를 쉽
www.inflearn.com
Table "USER" not found 에러
[SpringBoot] 스프링부트 로그인 구현- (2) Security 설정, Data 설정
401 unauthorized 해결을 위한 Security 설정 / Datasource, JPA 설정 / Entity 생성 / H2 콘솔 결과 확인
velog.io
'Java-Spring > Spring Boot JWT Tutorial' 카테고리의 다른 글
Spring Boot JWT Tutorial - 목차 (0) | 2023.07.03 |
---|---|
[Spring Boot JWT Tutorial] 회원가입, 권한검증 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] DTO, Repository, 로그인 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] JWT 코드, Security 설정 추가 (0) | 2022.01.23 |
[Spring Boot JWT Tutorial] JWT 소개, 프로젝트 생성 (0) | 2022.01.22 |