検索
ホームページJava&#&チュートリアルSpringBoot SpringSecurityの使い方

SpringBoot はユーザーのデフォルト構成を採用しており、Spring Security を迅速に開始するには pom 依存関係を導入するだけで済みます。
目的: リクエストしているユーザーの身元を確認し、安全なアクセスを提供します
利点: Spring に基づいており、設定が簡単で、多くのコードを削減します

SpringBoot SpringSecurityの使い方

ビルド-in アクセス制御メソッド

  • permitAll() は、一致した URL へのアクセスが誰でも許可されることを意味します。

  • authenticated() は、一致した URL にアクセスする前に認証が必要であることを意味します。

  • anonymous() は、一致する URL に匿名でアクセスできることを示します。この効果は、anonymous() に設定された URL がフィルタ チェーン内で

  • denyAll() を実行する点を除いて、permitAll() と似ています。一致する URL へのアクセスは許可されません。

  • rememberMe() 「私を覚えている」ユーザーは、多くの Web サイトと同様に、この Web サイトにアクセスできます。 10日間、一度ログインすると覚えていただけるので、しばらくログインする必要はありません。

  • fullAuthenticated() アクセスは、ユーザーが私のことを覚えていない場合にのみ可能です。つまり、段階的にログインする必要があります。

ロール権限の判断

  • hasAuthority(String) ユーザーが特定の権限を持っているかどうかを判断します。ユーザーの権限はカスタムです。ログイン ロジック

  • #hasAnyAuthority(String ...) ユーザーが指定されたアクセス許可のいずれかを持っている場合、アクセスが許可されます

  • hasRole(String)
  • ユーザーが指定されたロールを持っている場合、アクセスを許可します。それ以外の場合、403

  • hasAnyRole(String ...)
  • ユーザーが指定されたロールのいずれかを持っている場合、アクセスは許可されます

    ##hasIpAddress(String)
  • リクエストが指定された IP に対するものであれば、アクセスが実行されます。 request.getRemoteAddr()
  • 参照 Spring Security

  • Pom ファイルに追加する
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>vipsoft-parent</artifactId>
        <groupId>com.vipsoft.boot</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>vipsoft-security</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

パスワードのデフォルト ユーザーは、request.getRemoteAddr()を通じて IP アドレスを取得できます。実行後に自動的に生成される 名前: user

#デフォルト設定では、プロジェクトが開始されるたびにパスワードが再生成されます。同時に、ユーザー名とインターセプト リクエストは実行できません。実際のアプリケーションではカスタマイズ設定が必要になることが多いので、次に Spring Security のカスタム設定を行います。

SpringBoot SpringSecurityの使い方Spring Security の構成 (開始)

メモリ内で 2 つのユーザー ロール (管理者とユーザー) を構成し (プロセスを簡素化し、ロジックを理解するため)、異なるパスワードを設定します。ロールへのアクセスと同時に権限が付与されます。管理者はすべてのパス (つまり /*) にアクセスでき、ユーザーは /user の下のすべてのパスにのみアクセスできます。

カスタム構成クラス。

WebSecurityConfigurerAdapter

インターフェイス、
WebSecurityConfigurerAdapter

を実装します。インターフェイスでは 2 つの configure() メソッドが使用されます。1 つはユーザー ID を構成し、もう 1 つはユーザー ID を構成します。ユーザー権限を構成します:

configure() メソッドでユーザー ID を構成します: SecurityConfig

package com.vipsoft.web.config;
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(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 配置用户身份的configure()方法
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin")
                .password(passwordEncoder.encode("888"))
                .roles("ADMIN")
                .and()
                .withUser("user")
                .password(passwordEncoder.encode("666"))
                .roles("USER");
    }
    /**
     * 配置用户权限的configure()方法
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置拦截的路径、配置哪类角色可以访问该路径
                .antMatchers("/user").hasAnyRole("USER")
                .antMatchers("/*").hasAnyRole("ADMIN")
                //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面
                .and().formLogin();
    }
}

インターフェースのテストを追加

package com.vipsoft.web.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DefaultController {
    @GetMapping("/")
    @PreAuthorize("hasRole(&#39;ADMIN&#39;)")
    public String demo() {
        return "Welcome";
    }
    @GetMapping("/user/list")
    @PreAuthorize("hasAnyRole(&#39;ADMIN&#39;,&#39;USER&#39;)")
    public String getUserList() {
        return "User List";
    }
    @GetMapping("/article/list")
    @PreAuthorize("hasRole(&#39;ADMIN&#39;)")
    public String getArticleList() {
        return "Article List";
    }
}

以上がSpringBoot SpringSecurityの使い方の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は亿速云で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
Javaプラットフォームは独立していますか?Javaプラットフォームは独立していますか?May 09, 2025 am 12:11 AM

Javaは、Java Virtual Machines(JVMS)とBytecodeに依存している「Write and Averywherewherewherewherewherewherewhere」の哲学のために、プラットフォームに依存しません。 1)Javaコードは、JVMによって解釈されるか、地元でその場でコンパイルされたBytecodeにコンパイルされます。 2)ライブラリの依存関係、パフォーマンスの違い、環境構成に注意してください。 3)標準ライブラリを使用して、クロスプラットフォームのテストとバージョン管理がプラットフォームの独立性を確保するためのベストプラクティスです。

Javaのプラットフォームの独立性についての真実:それは本当に簡単ですか?Javaのプラットフォームの独立性についての真実:それは本当に簡単ですか?May 09, 2025 am 12:10 AM

java'splatformindepenceisnotsimple; itinvolvescomplexities.1)jvmcompatibilitymustbeensuredacrosplatforms.2)nativeLibrariesandsystemCallSneedCarefulHandling.3)依存症の依存症の依存症と依存症の依存症と依存関係の増加 - プラットフォームのパフォーマンス

Javaプラットフォームの独立性:Webアプリケーションの利点Javaプラットフォームの独立性:Webアプリケーションの利点May 09, 2025 am 12:08 AM

java'splatformentedentencebenefitswebapplicationsbyAllowingCodeTorunOnySystemwithajvm、simpledifyifieddeploymentandscaling.itenables:1)easydeploymentddifferentservers、2)Seamlessscalingacroscloudplatforms、および3)deminvermentementmentmentmentmentementtodeploymentpoce

JVM説明:Java Virtual Machineの包括的なガイドJVM説明:Java Virtual Machineの包括的なガイドMay 09, 2025 am 12:04 AM

jvmistheruntimeenvironment forexecutingjavabytecode、Curivalforjavaの「writeonce、runanywhere」capability.itmanagesmemory、executessuressecurity、makingestessentionentionalforjavadevadedertionserstunterstanderforeffication devitivationdevation

Javaの主な機能:なぜそれがトッププログラミング言語のままであるかJavaの主な機能:なぜそれがトッププログラミング言語のままであるかMay 09, 2025 am 12:04 AM

JavareMainsAtopChoiceFordevelopersDuetoitsPlatformEndepentence、Object-OrientedDesign、stryngting、automaticmemorymanagement、およびcomprehensivestandardlibrary.thesefeaturesmavaversatilatileandpowerful、sustableforawiderangeofplications、daspitesomech

Java Platform Independence:開発者にとってはどういう意味ですか?Java Platform Independence:開発者にとってはどういう意味ですか?May 08, 2025 am 12:27 AM

java'splatformentencemeansdeveloperscancancodecodeonceanddevicewithoutrocompilling.cancodecodecodecodecodecodecodecodecodecodecodecode compilling

最初の使用のためにJVMをセットアップする方法は?最初の使用のためにJVMをセットアップする方法は?May 08, 2025 am 12:21 AM

JVMをセットアップするには、次の手順に従う必要があります。1)JDKをダウンロードしてインストールする、2)環境変数を設定する、3)インストールの確認、4)IDEを設定する、5)ランナープログラムをテストします。 JVMのセットアップは、単に機能するだけでなく、メモリの割り当て、ガベージコレクション、パフォーマンスチューニング、エラー処理の最適化を行い、最適な動作を確保することも含まれます。

製品のJavaプラットフォームの独立性を確認するにはどうすればよいですか?製品のJavaプラットフォームの独立性を確認するにはどうすればよいですか?May 08, 2025 am 12:12 AM

toensurejavaplatformindopendence、soflowthesesteps:1)compileandrunyourapplicationOnMultiplePlatformsusingDifferentosAndjvversions.2)utilizeci/cdpipelines

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール