English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
인증 외에도 Spring Security는 로그인 사용자의 권한을 확인합니다. 로그인 후, 사용자의 ROLE에 따라 자원 접근 권한을 완료합니다.
WebSecurityConfig 클래스에서 사용자를 생성할 때, 사용자의 ROLE도 지정할 수 있습니다.
메서드 수준의 보안은 무단 접근자에 한해이며, 실제 사용자만 허용됩니다.
예제를 보여드리겠습니다. 먼저, Maven 프로젝트를 생성하여 자세한 정보를 제공합니다.
이 프로젝트는 처음에는 이렇게 보입니다:
지금, 프로그램을 설정하여 무단 접근과 인증되지 않은 사용자를 방지합니다. 이를 위해 아래에 제공된 네 개의 Java 파일이 필요합니다. 패키지 com.w를 생성합니다.3codebox를 그 안에 넣습니다.
//AppConfig.java
이 클래스는 뷰解析기를 통해 뷰의 접미사와 접두사를 설정하는 데 사용됩니다.
package com.w;3codebox; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.w3codebox.controller.*" }) public class AppConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
//MvcWebApplicationInitializer.java.java
package com.w;3codebox; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { WebSecurityConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // TOdo Auto-generated method stub return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
//SecurityWebApplicationInitializer.java
package com.w;3codebox; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
//WebSecurityConfig.java
이 클래스는 사용자를 생성하고 그 인증을 설정하는 데 사용됩니다. 사용자가 이 애플리케이션에 접근하려면 항상 로그인이 필요합니다.
package com.w;3codebox; import org.springframework.context.annotation.*; 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.*; import org.springframework.security.core.userdetails.*; import org.springframework.security.core.userdetails.User.UserBuilder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @EnableWebSecurity @ComponentScan("com.w3codebox) @EnableGlobalMethodSecurity(prePostEnabled=true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() {}} // public UserDetailsService userDetailsService() {}} ensure the passwords are encoded properly UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();123manager.createUser(users.username("irfan").password("user").roles("USER").build()); manager.createUser(users.username("admin").password("admin").roles("USER").build());123").roles("ADMIN").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(). antMatchers("/index","/").permitAll() .antMatchers("/admin","/user().authenticated() .and() .formLogin() .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } }
HomeController 컨트롤러를 생성하고 추가합니다. com.w3codebox.controller 패키지 내.
//HomeController.java;
package com.w;3codebox.controller; import org.springframework.security.access.prepost.PreAuthorize; 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.ResponseBody; @Controller public class HomeController { @RequestMapping(value="/, method=RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value="/user, method=RequestMethod.GET) public String user() { return "admin"; } @RequestMapping(value="/admin, method=RequestMethod.GET) public String admin() { return "admin"; } // Only, a person having ADMIN role can access this method. @RequestMapping(value="/update, method=RequestMethod.GET) @ResponseBody @PreAuthorize("hasRole('ROLE_ADMIN')") public String update() { return "record updated "; } }
创建以下视图(JSP页面)以为用户生成输出。将所有视图放入 WEB-INF/views 文件夹。
//index.jsp
<html> <head> <title>Home Page</title> </head> <body> Welcome to w3codebox! <br> <br> Login as: <a href="admin">Admin</a> <a href="user">User</a> </body> </html>
//admin.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> <span style="color: green">Login Successful!/span> ? <a href="logout" style="text-decoration: none;">로그아웃</a> <br> <br> <a href="update" style="text-decoration: none;">업데이트 기록</a> </body> </html>
이 프로젝트를 생성하기 위해 필요한 의존성은 다음과 같습니다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.w3codebox</groupId> <artifactId>springmethod</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
위의 모든 파일을 추가한 후, 우리의 프로젝트는 다음과 같습니다:
출력:
ADMIN 역할로 처음 로그인
로그인 후에
클릭 기록 업데이트그런 다음, 사용자의 역할이 ADMIN인지 확인하여 기록이 업데이트되었는지 확인하세요.
지금, 사용자로 로그인하세요.
지금, 클릭하세요 기록 업데이트사용자 역할이 USER라서 서버가 접근을 거부했습니다.