مشخصات مقاله
-
463
-
0.0
-
1789
-
0
-
0
آموزش امنیت در سطح متد در Java Spring
امنیت در سطح متد
امنیت Spring در سطح متد
علاوه بر احراز هویت، امنیت Spring مجوز کاربر وارد شده را نیز بررسی می کند. پس از ورود، بررسی مجوز کاربران برای دسترسی به منابع بر اساس نقش (ROLE) کاربر صورت می پذیرد. در زمان ایجاد کاربر در کلاس WebSecurityConfig ، می توان نقش کاربر را نیز مشخص کرد. امنیت اعمال شده روی یک متد، کاربر غیر مجاز را محدود می کند و تنها کاربر معتبر را مجاز می داند.
یک مثال ببینیم. ابتدا یک پروژه maven با ارائه جزییات ایجاد کنید.
پروژه در ابتدا به این شکل است.
پیکربندی امنیت Spring
حال، برای محافظت در مقابل کاربران غیر مجاز و نا معتبر، برنامه را پیکربندی کنید. به این منظور نیاز به چهار فایل جاوا داریم که در ادامه قرار داده شده است. پکیج com.javatpoint را ایجاد کنید و همه فایل ها را در آن قرار دهید.
// AppConfig.java
از این کلاس برای تنظیم پیشوند و پسوند منظر(view) با کمک view resolver استفاده می شود.
package com.javatpoint;
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.javatpoint.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
package com.javatpoint;
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.javatpoint;
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
// WebSecuiryConfig.java
از این کلاس برای ایجاد کاربر و تنظیم هویت آنها استفاده می شود. هر زمان که کاربر قصد دسترسی به برنامه را داشته باشد، ورود به سیستم لازم است.
package com.javatpoint;
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.javatpoint")
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("irfan").password("user123").roles("USER").build());
manager.createUser(users.username("admin").password("admin123").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.javatpoint.controller ایجاد کنید.
// HomeController.java
package com.javatpoint.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 ";
}
}
منظر ها (views)
منظر های(صفحات JSP) زیر را به منظور تولید خروجی برای کاربر ایجاد کنید. همه منظر ها را درون پوشه WEB-INF/views قرار دهید.
// index.jsp
< html> < head> < title>Home Page< /title> < /head> < body> Welcome to Javatpoint! < 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;">logout< /a> < br> < br> < a href="update" style="text-decoration: none;">Update Record< /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.javatpoint< /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>
ساختار پروژه
پس از اضافه کردن همه فایل های بالا، ساختار پروژه به این شکل می شود.
سرور را اجرا کنید.
خروجی :
در ابتدا به عنوان ادمین وارد شوید.
پس از ورود
روی گزینه به روز رسانی رکورد (update record) کلیک کنید و ببینید که رکورد به روز رسانی می شود زیرا نقش کاربر ادمین است.
ورود کاربر
حال به عنوان کاربر وارد شوید.
حال، روی گزینه به روز رسانی رکورد (update record) کلیک کنید. می بینید که سرور درخواست را نمی پذیرد زیرا نقش کاربر ، کاربر (USER) است.