웹사이트 검색

Spring Security 역할 기반 액세스 권한 부여 예제


오늘은 스프링 시큐리티 역할 기반 접근 및 권한 부여 예제에 대해 알아보겠습니다. 그러나이 게시물을 읽기 전에 \Spring 4 Security MVC 로그인 로그 아웃 예제\에 대한 이전 게시물을 통해 Spring 4 Security에 대한 기본 지식을 얻으십시오.

스프링 보안 역할

이번 포스트에서는 Spring Web Application에서 "USER\, "ADMIN\과 같은 스프링 보안 역할을 정의하고 사용하고 관리하는 방법에 대해 설명합니다. 이전 게시물과 마찬가지로 이 게시물 예제도 In-Memory Store 및 Spring Java Configuration Feature와 함께 Spring 4 MVC Security를 사용하여 애플리케이션을 개발하고 있습니다. 즉, 우리는 web.xml 파일을 사용하지 않을 것이며 Spring XML 구성의 한 줄도 작성하지 않을 것입니다. \In-Memory Store\ 옵션을 사용하여 사용자 자격 증명을 저장하고 관리할 것입니다. Spring 4.0.2.RELEASE, Spring STS 3.7 Suite IDE, Spring TC Server 3.1 with Java 1.8 및 Maven 빌드 도구를 사용하여 이를 개발할 것입니다. 예.

Spring Security 역할 기반 액세스 권한 부여 예제

  1. 다음 세부 정보를 사용하여 Spring STS Suite에서 "Simple Spring Web Maven\ 프로젝트를 만듭니다.\n프로젝트 이름 : SpringMVCSecruityMavenRolesApp2. 다음 변경 사항으로 이전 게시물의 동일한 pom.xml 파일을 사용합니다.

<artifactId>SpringMVCSecruityMavenRolesApp</artifactId>

<build>
  <finalName>SpringMVCSecruityMavenRolesApp</finalName>
</build>
</project>

  1. 이전 게시물의 모든 Java 및 JSP 파일을 사용합니다. 여기서는 업데이트되거나 새로 추가된 콘텐츠만 논의합니다.
  2. "USER” 및 "ADMIN”과 같은 사용자 역할을 구성하도록 LoginSecurityConfig.java 파일을 업데이트합니다.\nLoginSecurityConfig.java

package com.journaldev.spring.secuity.config;

import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
@EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
		authenticationMgr.inMemoryAuthentication()
			.withUser("jduser").password("jdu@123").authorities("ROLE_USER")
			.and()
			.withUser("jdadmin").password("jda@123").authorities("ROLE_USER","ROLE_ADMIN");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {

		
		http.authorizeRequests()
			.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
			.antMatchers("/userPage").access("hasRole('ROLE_USER')")
			.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
			.and()
				.formLogin().loginPage("/loginPage")
				.defaultSuccessUrl("/homePage")
				.failureUrl("/loginPage?error")
				.usernameParameter("username").passwordParameter("password")				
			.and()
				.logout().logoutSuccessUrl("/loginPage?logout"); 
		
	}
}

코드 설명

  1. configureGlobal() 메서드에서 두 명의 사용자를 추가했습니다. 한 명은 "ROLE_USER” 역할을 가진 사용자이고 다른 한 명은 "ROLE_USER” 및 "ROLE_ADMIN” 역할을 모두 가진 사용자입니다. 즉, 이 두 번째 사용자는 관리자 역할을 합니다. . 이와 같이 사용자와 역할을 얼마든지 구성할 수 있습니다.
  2. 권한(ROLE) 또는 역할(ROLE) 방법을 사용하여 애플리케이션에서 역할을 구성할 수 있습니다.
  3. authority()와 roles() 메소드의 차이점:

  • authorities()에는 "ROLE_USER\와 같은 완전한 역할 이름이 필요합니다.
  • roles()는 "USER\와 같은 역할 이름이 필요합니다. 이 "USER\ 역할 이름에 "ROLE_\ 값을 자동으로 추가합니다.

  1. configure() 메서드에서 필요한 액세스 역할을 가진 다른 URL을 정의했습니다.

antMatchers("/homePage")
   .access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")

이 코드 스니펫은 "/homePage”가 USER 및 ADMIN 역할 모두에 사용 가능하도록 구성합니다.

 .antMatchers("/userPage").access("hasRole('ROLE_USER')")
 .antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")

이 코드 스니펫은 "USER\ 역할만 "/userPage\에 액세스할 수 있고 "ADMIN\ 역할만 ."/adminPage”에 액세스할 수 있도록 구성합니다. 다른 역할이 이 페이지에 액세스하면 액세스 "403 액세스가 거부되었습니다.\ 오류 메시지가 표시됩니다.

  1. LoginController.java 컨트롤러 파일을 업데이트하여 아래와 같이 새 URL 액세스 경로를 정의합니다.\nLoginController.java

package com.journaldev.spring.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

	@RequestMapping(value = { "/"}, method = RequestMethod.GET)
	public ModelAndView welcomePage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("welcomePage");
		return model;
	}

	@RequestMapping(value = { "/homePage"}, method = RequestMethod.GET)
	public ModelAndView homePage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("homePage");
		return model;
	}
	
	@RequestMapping(value = {"/userPage"}, method = RequestMethod.GET)
	public ModelAndView userPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("userPage");
		return model;
	}
	
	@RequestMapping(value = {"/adminPage"}, method = RequestMethod.GET)
	public ModelAndView adminPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("adminPage");
		return model;
	}
	
	@RequestMapping(value = "/loginPage", method = RequestMethod.GET)
	public ModelAndView loginPage(@RequestParam(value = "error",required = false) String error,
	@RequestParam(value = "logout",	required = false) String logout) {
		
		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", "Invalid Credentials provided.");
		}

		if (logout != null) {
			model.addObject("message", "Logged out from JournalDEV successfully.");
		}

		model.setViewName("loginPage");
		return model;
	}

}

코드 설명 이전 게시물 예제 외에도 여기에 두 개의 새로운 URL을 추가했습니다.

  1. "/userPage”는 일반 사용자 활동에 액세스하고 수행하기 위해 USER 역할에서 사용됩니다.\n
  2. "/adminPage\는 관리자 역할에 의해 관리 사용자 활동에 액세스하고 수행하는 데 사용됩니다. ADMIN 역할은 "/userPage\ URL에도 액세스할 수 있습니다.\n
  3. 사용자 및 관리자 역할 특정 활동을 제공하도록 homePage.jsp 파일을 업데이트했습니다.\nhomePage.jsp

<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<a href="${pageContext.request.contextPath}/userPage">JD User</a> | <a href="${pageContext.request.contextPath}/adminPage">JD Admin</a> | <a href="javascript:document.getElementById('logout').submit()">Logout</a>

<h3>Welcome to JournalDEV Tutorials</h3>
<ul>
   <li>Java 8 tutorial</li>
   <li>Spring tutorial</li>
   <li>Gradle tutorial</li>
   <li>BigData tutorial</li>
</ul>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>

여기에 상단 프레임에 옵션과 같은 세 가지 메뉴를 추가했습니다. "로그아웃\은 이전 게시물에서 이미 설명했습니다. 새로운 두 링크는 다음과 같습니다.

  1. JD 사용자: "USER\ 및 "ADMIN\ 역할 모두에서 액세스 가능
  2. JD Admin: 두 "ADMIN\ 역할만 액세스 가능

참고:- 실시간 애플리케이션에서는 "사용자\ 역할에 대한 "JD 사용자\ 링크만 표시하고 "JD 관리자\ 링크는 숨깁니다. "사용자\ 역할이 액세스할 수 있는지 여부를 테스트하기 위해 정확한 오류 메시지를 보려면 이 링크를 숨기지 않았습니다.20. "ADMIN\ 역할의 홈페이지 역할을 할 새 adminPage.jsp 파일을 추가합니다.

<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<h3>Welcome to JournalDEV Tutorials</h3>
<h3>Admin Page</h3>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
	<a href="javascript:document.getElementById('logout').submit()">Logout</a>
</c:if>

  1. "사용자\ 역할의 홈페이지 역할을 할 새 userPage.jsp 파일을 추가합니다.\nuserPage.jsp

<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<h3>Welcome to JournalDEV Tutorials</h3>
<h3>User Page</h3>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
	<a href="javascript:document.getElementById('logout').submit()">Logout</a>
</c:if>

이제 애플리케이션 개발을 완료했습니다. 프로젝트 최종 구조를 확인하고 애플리케이션을 테스트할 시간입니다.26. 최종 프로젝트 구조는 다음과 같습니다.

스프링 보안 역할 예제 애플리케이션 테스트

이것이 웹 애플리케이션 페이지에 대한 인증된 액세스를 제공하는 Spring 보안 역할 예제에 관한 것입니다.