JQueryBootStrap을 제작사 홈페이지에서 다운로드 받아 추가하는 방법 이외에 Mavendependencyscript만 추가하여 주면 프로젝트에 추가를 할 수 있습니다스크립트는 일반 예제에서 복사해 와도 되지만 프로젝트 별로 사용할 버전을 선택 해야 하기 때문에 그냥 복사하기 보다는 공신력이 있는 사이트를 이용해서 참조를 하는것이 좋습니다여기서 2곳의 사이트를 소개합니다.

 

https://mvnrepository.com/


mvnrepository.com에서는 라이브러리를 검색을 통하여 찾을 수 있습니다


maven jquery bootstrap


귀찮기는 하지만 검색을 하면 버전 별로 정보가 리스트 되고 리스트에서 원하는 버전을 선택 하면


maven jquery bootstrap


스크립트를 복사해올 수 있습니다. Gradle을 클릭 하면 Gradle용 스크립트가 나옵니다.

 


https://www.webjars.org/

 

webjars.org에서는 첫 화면에 자주 사용하는 라이브러리가 리스트 되어 있고 최신 버전으로 스크립트를 얻을 수 있습니다.


maven jquery bootstrap


만약 최신 버전이 아닌 예전 버전이 필요하다면 콤보 박스를 클릭하면 해당 라이브러지의 버전 정보가 리스트 되고 원하는 버전을 선택하여 


maven jquery bootstrap


상단 Build Tool:에 있는 Maven 버튼을 선택하면 스크립트를 얻을 수 있습니다.

 

복사한 스크립트는 pom.xml에 추가를 해줍니다.


                <dependency>

                   <groupId>org.webjars</groupId>

                   <artifactId>jquery</artifactId>

                   <version>3.4.1</version>

               </dependency>

               <dependency>

                   <groupId>org.webjars</groupId>

                   <artifactId>bootstrap</artifactId>

                   <version>4.4.1</version>

               </dependency>


그리고 Maven UpdateMaven install을 하면 추가된 라이브러리를 jsp에 사용할 수 있게 됩니다.

 

js 파일 위치


추가한 라이브러리를 jsp에서 사용하기 위한 path는 어떻게 하면 알 수 있을까요추가된 라이브러리의 .jar 파일을 확장하면 정확한 js 파일 위치를 찾을 수 있습니다.


maven jquery bootstrap


이렇게 찾은 위치를 script에 반영하면 됩니다.

<script src="/webjars/jquery/3.4.1/jquery.min.js"></script>

 

bootstrap도 동일한 방법으로 위치를 확인 합니다.


maven jquery bootstrap


그리고 스크립트에 반영 합니다. bootstrap은 기본 제공 css를 사용하려면 cssjs를 모두 반영합니다.

<script src="/webjars/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="/webjars/bootstrap/4.4.1/css/bootstrap.min.css">

 

사용 예

 

간단하게 JSP파일을 생성해서 잘 반영이 되었는지 사용을 해 봅니다.


 <%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

 

<link rel="stylesheet" href="/webjars/bootstrap/4.4.1/css/bootstrap.min.css">

<script src="/webjars/jquery/3.4.1/jquery.min.js"></script>

<script src="/webjars/popper.js/1.16.0/umd/popper.min.js"></script>

<script src="/webjars/bootstrap/4.4.1/js/bootstrap.min.js"></script>

 

</head>

<body>

 

<div class="container">

 

<table class="table table-hover">

  <thead class="thead-dark">

    <tr>

      <th>codeId</th>

      <th>code</th>

      <th>codeNm</th>

      <th>codeDc</th>

    </tr>

  </thead>

  <tbody>

    <tr>

        <td>COM001</td>

        <td>REGC01</td>

        <td>단일 게시판 이용등록</td>

        <td>단일 게시판 이용등록</td>

        </tr>

    <tr>

        <td>COM001</td>

        <td>REGC02</td>

        <td>커뮤니티 등록</td>

        <td>커뮤니티 등록</td>

    </tr>

    <tr>

        <td>COM001</td>

        <td>REGC03</td>

        <td>동호회 등록</td>

        <td>동호회 등록</td>

    </tr>

    <tr>

        <td>COM001</td>

        <td>REGC04</td>

        <td>명함등록</td>

        <td>명함등록</td>

    </tr>          

  </tbody>

 

</table>

  

</div>

</body>

</html>


maven jquery bootstrap


잘 나오는 군요.  bootstrap을 사용하면 디자인을 없이도 어느 정도의 퀄리티 있는 사이트 제작이 가능 합니다.


- copy coding -


Spring Boot에서 jsp로 화면을 만들고 Controller에서 View로 리턴을 하였는데 jsp 파일을 찾지 못하는 경우 ResourceHttpRequestHandler :Path with "WEB-INF" or "META-INF" 이런 식으로 발생하는 오류입니다브라우저에는 아래와 같은 오류가 발생 하고


spring boot jasper


Console에도 아래 처럼 오류 로그를 확인할 수 있습니다


spring boot jasper


spring boot jasper


2020-02-14 11:54:00.941  INFO 33124 --- [nio-9090-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...

2020-02-14 11:54:01.089  INFO 33124 --- [nio-9090-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

2020-02-14 11:54:01.151  WARN 33124 --- [nio-9090-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/board/BoardList.jsp]

2020-02-14 11:54:05.743  WARN 33124 --- [nio-9090-exec-2] o.s.w.s.r.ResourceHttpRequestHandler     : Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/welcome.jsp]


사실 오류라기 보다는 Spring Boot에서 내장된 Tomcat을 사용 하는 경우 JSP를 처리하는 서블릿을 추가하지 않아 발생하는 것으로 pom.xml에 다음을 추가해 주면 해결 됩니다.


 <dependency>

        <groupId>org.apache.tomcat.embed</groupId>

        <artifactId>tomcat-embed-jasper</artifactId>

</dependency>


pom.xml에 추가하고  Maven update 하고 Maveninstall 하고 실행해 보면 이번에는 화면에 출력이 잘 나옵니다.



Spring Security에서의 권한 별 접근은 아래 source 처럼 대부분 configure(HttpSecurity http)에 설정을 하여 관리를 하게 됩니다.


   @Override

   protected void configure(HttpSecurity http) throws Exception {

      http.httpBasic().and().authorizeRequests()

        .antMatchers("/").permitAll()

        .antMatchers("/page2").hasRole("ADMIN")

        .antMatchers("/page1").hasRole("USER")

        .anyRequest().authenticated()

        .and().logout().permitAll()

        .and().formLogin()

        .and().csrf().disable();

  }


다른 방법을 찾아보면 Controllerannotation을 추가하여 관리하는 방법도 있는데 이것이 @PreAuthorize, @PostAuthorize, @Secured 입니다사용 방법도 너무나 간단한데 권한 설정이 필요한 위치에 @PreAuthorize("hasRole('ROLE_ADMIN')") 이런식으로 어노테이션을 추가해 주면 권한 별로 접근을 통제 하게 됩니다예를 들자면...


    @PreAuthorize("hasRole('ROLE_ADMIN')")

    @RequestMapping("/preRole1")

    public @ResponseBody String preRole1() throws Exception {

              

           return "@PreAuthorize : get role ROLE_ADMIN";

    }


위에있는 예제처럼 추가를 하였는데 아무런 작동을 하지 않는다면 @PreAuthorize @Secured의 사용은 처음에는 비활성화 되어 있어서 사용 하려면 설정을 해줘야 됩니다이것도 아주 간단 한데 Configure 클래스 파일 상단에 아래 코드를 추가해 주기만 하면 활성화 됩니다.

@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)



테스트


몇가지 예를 들어 간단하게 테스트를 해보겠습니다.

 

copycodingADMIN 권한이고 honggil이는 USER 권한을 가지도록 configure에 설정을 합니다.


 @Autowired

 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()

        .withUser("copycoding").password(passwordEncoder().encode("copycopy")).roles("ADMIN");

    auth.inMemoryAuthentication()

        .withUser("honggil").password(passwordEncoder().encode("hoho")).roles("USER");

 }


Method에는 annotation을 사용하여 각 권한 별로  접근 설정을 합니다.


 @PreAuthorize("hasRole('ROLE_ADMIN')")

 @RequestMapping("/preRole1")

 public @ResponseBody String preRole1() throws Exception {

              

              return "@PreAuthorize : get role ROLE_ADMIN";

 }

       

 @PreAuthorize("hasRole('ROLE_USER')")

 @RequestMapping("/preRole2")

 public @ResponseBody String preRole2() throws Exception {

              

               return "@PreAuthorize : get role ROLE_USER";

 }

       

 @Secured("ROLE_ADMIN")

 @RequestMapping("/secRole1")

 public @ResponseBody String secRole1() throws Exception {

              

               return "@Secured : get role ROLE_ADMIN";

 }

 

 @Secured("ROLE_USER")

 @RequestMapping("/secRole2")

 public @ResponseBody String secRole2() throws Exception {

              

               return "@Secured : get role ROLE_USER";

 }



@PreAuthorize 테스트


ADMIN 권한이 있는 copycoding으로 로그인을 진행 합니다.


Spring Security PreAuthorize Secured


로그인이 성공 하면 http://localhost:9090/preRole1 에 접속해 봅니다


Spring Security PreAuthorize Secured


접근 권한이 있으니 접근을 할 수 있습니다.


그러면 이번엔 http://localhost:9090/preRole2 에 접속 합니다.


Spring Security PreAuthorize Secured


ADMIN만 접근 가능하니 USER 권한으로는 접근이 불가능 합니다


 

@Secured 테스트

 

USER 권한이 있는 honggil로 로그인을 하고 http://localhost:9090/secRole1 를 호출 합니다.


Spring Security PreAuthorize Secured


ADMIN만 접근 권한이 있으므로 접속이 차단 됩니다.

 

이번엔 http://localhost:9090/secRole2에 접속하면


Spring Security PreAuthorize Secured


USER 권한을 가지고 있어 접속이 가능 합니다.


configure를 이용하는 방법과 annotation을 이용하는 방법의 차이는 접근 권한을 한곳에서 관리 하느냐 여러곳에서 필요에 따라 관리하느냐 하는 관리적인 관점의 차이인데 프로젝트에 따라서 선택을 하던가 적절히 섞어서 사용 하던가 하면 될것 같습니다.

 

@PreAuthorize 와 쌍으로 @PostAuthorize 도 있습니다차이점은 @PreAuthorize 는 말 그대로 실행 전에 권한을 검사하는 거고 @PostAuthorize 는 실행 후 권한을 검사하는 건데 이것도 필요에 따라 선택을 하면 되겠죠.


전체 소스

WebSecurityConfigurerAdapter

package com.copycoding.security;

 

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 org.springframework.security.crypto.password.PasswordEncoder;

 

@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 

        @Override

        protected void configure(HttpSecurity http) throws Exception {

               http.httpBasic().and().authorizeRequests()

        .antMatchers("/").permitAll()

        .antMatchers("/page2").hasRole("ADMIN")

        .antMatchers("/page1").hasRole("USER")

        .anyRequest().authenticated()

        .and().logout().permitAll()

        .and().formLogin()

        .and().csrf().disable();

        }

       

        @Autowired

        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

               auth.inMemoryAuthentication()

                       .withUser("copycoding").password(passwordEncoder().encode("copycopy")).roles("ADMIN");

               auth.inMemoryAuthentication()

                       .withUser("honggil").password(passwordEncoder().encode("hoho")).roles("USER");

        }

       

        @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

} 


Controller

 package com.copycoding.security;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

 

import org.springframework.security.access.annotation.Secured;

import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class TestController {

       

        @RequestMapping("/")

    public @ResponseBody String home() throws Exception {

 

               return "Spring Boot ";

        }

       

        @RequestMapping("/page1")

    public @ResponseBody String pageNo1(HttpSession session, HttpServletRequest request) throws Exception {

              

               System.out.println("pageNo1=========ROLE_ADMIN===========>" + request.isUserInRole("ROLE_ADMIN"));

               System.out.println("pageNo1=========ROLE_USER============>" + request.isUserInRole("ROLE_USER"));

 

               return "Spring Boot : Page No 1";

        }

       

        @RequestMapping("/page2")

    public @ResponseBody String pageNo2(HttpSession session, HttpServletRequest request) throws Exception {

              

               System.out.println("pageNo2=======ROLE_ADMIN=============>" + request.isUserInRole("ROLE_ADMIN"));

               System.out.println("pageNo1=======ROLE_USER==============>" + request.isUserInRole("ROLE_USER"));

              

               return "Spring Boot : Page No 2";

        }

       

        @PreAuthorize("hasRole('ROLE_ADMIN')")

        @RequestMapping("/preRole1")

    public @ResponseBody String preRole1() throws Exception {

              

               return "@PreAuthorize : get role ROLE_ADMIN";

        }

       

        @PreAuthorize("hasRole('ROLE_USER')")

        @RequestMapping("/preRole2")

    public @ResponseBody String preRole2() throws Exception {

              

               return "@PreAuthorize : get role ROLE_USER";

        }

       

        @Secured("ROLE_ADMIN")

        @RequestMapping("/secRole1")

    public @ResponseBody String secRole1() throws Exception {

              

               return "@Secured : get role ROLE_ADMIN";

        }

 

        @Secured("ROLE_USER")

        @RequestMapping("/secRole2")

    public @ResponseBody String secRole2() throws Exception {

              

               return "@Secured : get role ROLE_USER";

        }

}


- copy coding -


Spring Boot를 이용하여 security를 적용하는 방법을 연습해 봅니다.

먼저 프로젝트를 생성해야 테스트를 진행 하겠죠.


spring boot security


상단 메뉴에서 File > New > Spring Starter Project를 이용하여 프로젝트를 생성해도 됩니다.


spring boot security


프로젝트 정보는 테스트용이라 대충 적었습니다.


spring boot security


필요한 라이브러리는 Spring Security만 설명할거기 때문에 복잡하지 않도록 Spring SecuritySpring Web만 선택 했습니다그리고 Finish 버튼을 클릭 하면 자동으로 필요한 라이브러리를 추가하고 기본 소스를 생성 합니다.

 

자동으로 생성된 프로젝트를 실행 해 볼까요?


spring boot security


Spring Boot App을 선택해서 실행을 합니다.


spring boot security


로그인 화면이 나오는데 IDsecurity에서 제공하는 초기값이 user 이고 비밀 번호는 Console 창에 출력을 해줍니다.


spring boot security


이렇게 console 창에 비밀번호가 나타납니다.  복사해서 비밀번호 입력을 하고  Sign in 버튼을 클릭하면 로그인이 진행 됩니다.


spring boot security


오류 메시지가 나오는군요그럼 로그인 성공 입니다.

가야할 페이지가 없어서 나오는 오류 입니다.  프로젝트만 생성하고 화면 작업을 하나도 안했죠.


그럼 갈곳을 정해주고 다시 해봅니다.

Controller 파일을 하나 생성하고


package com.copycoding.security;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;


@RestController

public class TestController {

@RequestMapping("/")

    public @ResponseBody String home() throws Exception {

return "Spring Boot";

}



@RestController 어노테이션을 사용합니다화면 만들기 귀찮아 텍스트를 바로 화면으로 출력하도록 했습니다. 홈페이지에 가려고 하는 경우 Spring Boot를 출력하도록 했습니다. 이러면 로그인 하고 여기로 오겠죠.

다시 프로젝트를 실행하고 로그인을 해봅니다.


spring boot security


로그인 성공입니다.

 

이번에는 페이지를 여러개 만들어서 테스트 합니다.

 

package com.copycoding.security;

 

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class TestController {

       

        @RequestMapping("/")

    public @ResponseBody String home() throws Exception {

 

               return "Spring Boot ";

        }

       

        @RequestMapping("/page1")

    public @ResponseBody String pageNo1() throws Exception {

              

               return "Spring Boot : Page No 1";

        }

       

        @RequestMapping("/page2")

    public @ResponseBody String pageNo2() throws Exception {

              

               return "Spring Boot : Page No 2";

        }

}

 

프로젝트를 실행해서 로그인 하고 각 페이지에 접근해 봅니다.


spring boot security


spring boot security


또 성공입니다로그인만 되면 아무 페이지나 막 갈 수 있습니다이러려고 Spring Security를 사용하는게 아니죠?


이번엔 갈 수 있는 페이지와 없는 페이지를 한정해 봅니다그러려면 class 파일을 하나 만들어야 합니다파일에 Security Config를 설정해서 테스트를 진행 합니다.

클래스를 하나 생성 하는데 상속을 받아서 생성을 해야 합니다.


spring boot security


바로 WebSecurityConfigurerAdapter를 찾아서 상속 관계를 만들어 줍니다생성하는 파일명은 편하게 만들면 되고 파일이 만들어 지면 상속된 클래스로 부터 Method 리스트를 찾아 추가해야 합니다.


spring boot security


Method 중에 configure(HttpSecurity http)를 선택하여 추가해 줍니다.  찾기 귀찮으면 그냥 직접 입력 해서 사용 합니다.


 package com.copycoding.security;


import org.springframework.context.annotation.Configuration;

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;


@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


@Override

protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

        .antMatchers("/").permitAll()

        .antMatchers("/page2").hasRole("ADMIN")

        .antMatchers("/page1").hasRole("USER")

        .anyRequest().authenticated();

}

}


Method가 추가 되면 페이지별 권한을 설정 합니다.

“/”는 로그인 하면 접근이 가능하고 다른 페이지 “page1”, “page2”는 아래와 같이 접속 하려면 오류가 발생 합니다.


spring boot security


잠시 Postman으로 설명을 하면


spring boot security


“/”는 접근이 가능 하지만


spring boot security


이렇게 “/page1”, “/page2”ADMIN USER 권한이 있어야 접속이 가능하므로 “Access Denied” 오류가 발생 합니다.

 

이제 ADMIN USER 권한이 있는 로그인 정보를 source에 추가해서 테스트 해보겠습니다.


 package com.copycoding.security;


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.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 org.springframework.security.crypto.password.PasswordEncoder;


@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


@Override

protected void configure(HttpSecurity http) throws Exception {

http.httpBasic().and().authorizeRequests()

        .antMatchers("/").permitAll()

        .antMatchers("/page2").hasRole("ADMIN")

        .antMatchers("/page1").hasRole("USER")

        .anyRequest().authenticated()

        .and().logout().permitAll()

        .and().formLogin()

        .and().csrf().disable();

}

@Autowired

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.withUser("copycoding").password(passwordEncoder().encode("copycopy")).roles("ADMIN");

auth.inMemoryAuthentication()

.withUser("honggil").password(passwordEncoder().encode("hoho")).roles("USER");

}

@Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

}


“/”는 아무나 접근 가능 합니다.

“/page2”“ADMIN” 권한이 있어야 하는데 아래에 id/pw“copycoding”, ”copycopy” 이고

“/page1” “USER” 권한으로 로그인 정보가 “honggil”, “hoho” 이면 된다고 했습니다.

Postman으로 id password를 전송해서 테스트를 해 봅니다.


spring boot security


ADMIN 권한으로 로그인이 되어서 “/page2”에 잘 접속이 됩니다.


spring boot security


ADMIN 권한으로는 “/page1” 접근은 어림 없군요.

 

logout을 하고 honggil로 로그인 하면 반대의 결과가 나옵니다.

결과는 생략 하겠습니다.

 

logout“.and().logout().permitAll()” 이렇게 설정을 해놓았으므로 사용이 가능하고 사용하는 방법은 다음처럼 http://localhost:9090/logout 을 입력 하면 됩니다.


spring boot security


회원 로그인과 권한을 메모리에 넣고 사용하는 방법으로 테스트를 했는데 이걸 Database에 넣어서 관리하면 되겠네요.  그건 다음에 시간이 되면 테스트 해보겠습니다.


- copy coding -


1···17181920212223···61

+ Recent posts