Giter Site home page Giter Site logo

mycfrservice's People

Contributors

mysm0722 avatar

Watchers

 avatar  avatar

mycfrservice's Issues

Spring Boot Data

스프링 데이터 11부 - Neo4j

신규 프로젝트 생성(springdataneo4j)

Neo4j 는 노드간의 연관 관계를 영속화하는데 유리한 그래프 데이터베이스

의존성 추가

  • spring-boot-starter-data-neo4j

(pom.xml)

...
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-neo4j</artifactId>
		</dependency>
...
  • Neo4j 설치 및 실행 (도커)
 $ docker run -p 7474:7474 -p 7687:7687 -d--name noe4j_boot neo4j 

image

  • http://localhost:7474/browser
    image
  • 초기 username/password는 neo4j/neo4j
    image
    -application.properties 파일에 neo4j 관련 계정 설정을 해야함

(application.properties)

spring.data.neo4j.password=1111
spring.data.neo4j.username=neo4j

Neo4jRunner Application 생성 및 실행

(Neo4jRunner.java)

package me.darrel.springdataneo4j;

import me.darrel.springdataneo4j.account.Account;
import me.darrel.springdataneo4j.account.Role;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class Neo4jRunner implements ApplicationRunner {

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Account account = new Account();
        account.setEmail("[email protected]");
        account.setUsername("general");

        Role role = new Role();
        role.setName("admin");

        account.getRoles().add(role);

        Session session = sessionFactory.openSession();
        session.save(account);
        sessionFactory.close();

        System.out.println("Finished");
    }
}

(Account.java)

package me.darrel.springdataneo4j.account;

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;

import java.util.HashSet;
import java.util.Set;

@NodeEntity
public class Account {

    @Id @GeneratedValue
    private Long Id;

    private String username;

    private String email;

    @Relationship(type = "has")
    private Set<Role> roles = new HashSet<>();

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

(Role.java)

package me.darrel.springdataneo4j.account;

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;

@NodeEntity
public class Role {
    @Id @GeneratedValue
    private Long Id;

    private String name;

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

애플리케이션을 실행하면 아래와 같이 Neo4j에 Releationship을 가진 테이블이 생성됨
image

위의 애플케이션을 Neo4jRepository를 사용하여 변경함

(Neo4jRunner.java)

package me.darrel.springdataneo4j;

import me.darrel.springdataneo4j.account.Account;
import me.darrel.springdataneo4j.account.AccountRepository;
import me.darrel.springdataneo4j.account.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class Neo4jRunner implements ApplicationRunner {

    @Autowired
    AccountRepository accountRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        Account account = new Account();
        account.setEmail("[email protected]");
        account.setUsername("user");

        Role role = new Role();
        role.setName("user");

        account.getRoles().add(role);
        accountRepository.save(account);

        System.out.println("Finished");
    }
}

(AccountRepository.java)

package me.darrel.springdataneo4j.account;

import org.springframework.data.neo4j.repository.Neo4jRepository;

public interface AccountRepository extends Neo4jRepository<Account, Long> {
}

애플리케이션을 실행하면 아래와 같이 Neo4j에 Releationship을 가진 테이블이 생성됨
image

스프링 데이터 Neo4J

  • Neo4jTemplate (Deprecated)
  • SessionFactory
  • Neo4jRepository

스프링 데이터 12부 - 정리

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-sql

스프링 시큐리티 1부 - spring-boot-starter-security

스프링 시큐리티

  • 웹 시큐리티
  • 메소드 시큐리티
  • 다양한 인증 방법 지원
    • LDAP, Form, Authority, Basic Auth, OAuth ...

스프링 부트 시큐리티 자동 설정

  • SecurityAutoConfiguration : Spring Framework에서 제공하는 기본 Security 설정 사용
  • UserDetailsServiceAutoConfiguration : User Manager 객체 생성 후 인메모리에서 관리함
    • Custom하게 사용하고 싶다면 UserDetailsService를 생성하여 빈으로 등록하면 됨
  • spring-boot-starter-security
    • 스프링 시큐리티 5.x 의존성 추가
  • 모든 요청에 인증이 필요함
  • 기본 사용자 생성
    • Username: user
    • Password : 애플리케이션을 실행할 때 마다 랜덤값 생성(콘솔에 출력)
    • spring.security.user.name
    • spring.security.user.password
  • 인증 관련 각종 이벤트 발생
    • DefaultAuthenticationEventPublisher 빈 등록
    • 다양한 인증 에러 핸들러 등록 가능

스프링 부트 시큐리티 테스트

https://docs.spring.io/spring-security/site/docs/current/reference/html5/#test

새 프로젝트 생성(springbootsecurity, Web 모듈만 추가)

기본적인 Controller/Templates/Test코드를 작성함

(HomeController.java)

package me.darrel.springbootsecurity;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/my")
    public String my() {
        return "my";
    }
}

(HomeControllerTest.java)

package me.darrel.springbootsecurity;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@RunWith(SpringRunner.class)
@WebMvcTest
public class HomeControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        mockMvc.perform(get("/hello"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("hello"));
    }

    @Test
    public void my() throws Exception {
        mockMvc.perform(get("/my"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("my"));
    }
}

(~/templates/index.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Welcome</h1>
<a href="/hello">Hello</a>
<a href="/my">My</a>
</body>

</html>

(~/templates/hello.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>

(~/templates/my.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My</title>
</head>
<body>
<h1>My</h1>
</body>
</html>

스프링 부트 시큐리티/Thymeleaf 의존성 추가

(pom.xml)

...
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
...

위의 의존성만 추가해도 기본적인 보안을 요구하므로, 위의 테스트 코드는 실패함

image

브라우저에서 실행하면 아래와 같이 기본적인 로그인 페이지로 이동함

(스프링 부트에서 자동설정에 의해 생성됨)

image

기본적인 Username은 user이며, Password는 애플리케이션 실행 시 랜덤하게 생성됨
image

실패하는 테스트를 정상적으로 실행하기 위해 아래와 같이 작성함

의존성을 추가함

(pom.xml)

...
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<version>${spring-security.version}</version>
			<scope>tet</scope>
		</dependency>
...

각 메소드 또는 클래스에 @WithMockUser를 추가하면 정상적으로 동작함

...
 @Test
    @WithMockUser
    public void hello() throws Exception {
        mockMvc.perform(get("/hello")
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.