English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Springメソッドレベルのセキュリティ

認証の他に、Spring Securityは、ログインしたユーザーの認可をチェックします。ログイン後、ユーザーのROLEに基づいて、リソースへのアクセスを許可する操作が完了します。

WebSecurityConfigクラスでユーザーを作成する際には、ユーザーのROLEも指定できます。

メソッドのセキュリティは、認証されていないユーザーに限られており、本物のユーザーのみが許可されます。

例を一つ見てみましょう。まず、詳細を提供してMavenプロジェクトを作成します。



このプロジェクトは最初はこんな感じでした:



Spring security設定

現在、アプリケーションを設定して未認証および認証されていないユーザーを防ぐために、以下に示される四个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() {  
        // 待办自动-生成方法存根  
        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.w"3codebox")  
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
@Bean  
public UserDetailsService userDetailsService() {}}
    // パスワードが適切にエンコードされることを確認する
     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.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";  
    }
    // このメソッドにアクセスできるのは、ADMIN ロールを持つ人だけです。
    @RequestMapping(value="/update", method=RequestMethod.GET) 
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String update() {  
        return "レコード 更新 成功";  
    }
}

ビュー

以下のビュー(JSPページ)をユーザー出力のために作成します。すべてのビューを WEB-INF/views フォルダー。

//index.jsp

<html>  
<head>  
<title>ホーム ページ</title>  
</head>  
<body>  
ようこそ w3codebox! <br> <br>
ログイン して: 
<a href="admin">管理者</a> <a href="user">ユーザー</a>
</body>  
</html>

//admin.jsp

<html>  
<head>  
<meta http-equiv="Content-Type-Type" content="text/html; charset=UTF-8-8">  
<title>ホーム ページ</title>  
</head>  
<body>  
<span style="color: green">ログイン 成功!/span> ? <a href="logout" style="text-装飾: 無;">ログアウト</a> <br> <br>
<a href="update" style="text-装飾: 無;/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</plugin>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>  
    <maven.compiler.target>1<version>8</maven.compiler.target>  
    <maven.compiler.source>1<version>8</maven.compiler.source>  
</properties>  
<dependencies>  
  <dependency>  
            <groupId>org.springframework</<groupId>  
            <artifactId>spring-webmvc</plugin>  
            <artifactId>5.0.2.RELEASE</version>  
        </  
        <dependency>  
        <groupId>org.springframework.security</<groupId>  
        <artifactId>spring-security-web</plugin>  
        <artifactId>5.0.0.RELEASE</version>  
    </  
<dependency>
    <groupId>org.springframework.security</<groupId>
    <artifactId>spring-security-core</plugin>
    <artifactId>5.0.4.RELEASE</version>
</
    -- ////org.springframework.security/-security-config --
<dependency>
    <groupId>org.springframework.security</<groupId>
    <artifactId>spring-security-config</plugin>
    <artifactId>5.0.4.RELEASE</version>
</
-- /////-beans --
        -- ////javax.servlet/javax.servlet-api --  
<dependency>  
    <groupId>javax.servlet</<groupId>  
    <artifactId>javax.servlet-api</plugin>  
    <artifactId>3<version>1.0</version>  
    <scope>provided</scope>  
</  
<dependency>  
    <groupId>javax.servlet</<groupId>  
    /plugin>  
    <artifactId>1<version>2</version>  
</  
-- /////-- --
</  
    
      
          
            <plugin>/<groupId>  
            <artifactId>maven-war-<artifactId>/plugin>  
            <artifactId>2<version>6</version>
                   <configuration>  
                <failOnMissingWebXml>false<//failOnMissingWebXml>  
            </configuration>  
        </plugin>  
    </plugins>  
  </build>  
</project>

プロジェクト構造

上記のすべてのファイルを追加後、プロジェクトは以下のようになります:



サーバーを実行します

出力:



初めてADMINとしてログイン



ログイン後、



クリック 更新履歴、その後、ユーザーのロールがADMINであるため、レコードが更新されたか確認してください。



ユーザーログイン

今、ユーザーとしてログインします。




今、 更新履歴、ユーザーロールがUSERであるため、サーバーはアクセスを拒否しました。