SpringBoot는 사용자를 위해 기본 구성을 채택했습니다. Spring Security를 빠르게 시작하려면 pom 종속성을 도입하기만 하면 됩니다.
목적: 요청하는 사용자의 신원을 확인하고 안전한 액세스 제공
장점: Spring 기반, 구성이 쉬움, 많은 코드 감소
내장 액세스 제어 방법
permitAll( )
는 일치하는 URL을 나타내며 누구나 액세스할 수 있습니다.permitAll()
表示所匹配的 URL 任何人都允许访问。authenticated()
表示所匹配的 URL 都需要被认证才能访问。anonymous()
表示可以匿名访问匹配的 URL 。和 permitAll() 效果类似,只是设置为 anonymous() 的 url 会执行 filter 链中denyAll()
表示所匹配的 URL 都不允许被访问。rememberMe()
被“remember me”的用户允许访问 这个有点类似于很多网站的十天内免登录,登陆一次即可记住你,然后未来一段时间不用登录。fullyAuthenticated()
如果用户不是被 remember me 的,才可以访问。也就是必须一步一步按部就班的登录才行。
角色权限判断
hasAuthority(String)
判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑hasAnyAuthority(String ...)
如果用户具备给定权限中某一个,就允许访问hasRole(String)
如果用户具备给定角色就允许访问。否则出现 403hasAnyRole(String ...)
如果用户具备给定角色的任意一个,就允许被访问hasIpAddress(String)
如果请求是指定的 IP 就运行访问。可以通过 request.getRemoteAddr() 获取 ip 地址
引用 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>
运行后会自动生成 password 默认用户名为: user
默认配置每次都启动项目都会重新生成密码,同时用户名和拦截请求也不能自定义,在实际应用中往往需要自定义配置,因此接下来对Spring Security进行自定义配置。
配置 Spring Security (入门)
在内存中(简化环节,了解逻辑)配置两个用户角色(admin和user),设置不同密码;
同时设置角色访问权限,其中admin可以访问所有路径(即/*),user只能访问/user下的所有路径。
自定义配置类,实现WebSecurityConfigurerAdapter
接口,WebSecurityConfigurerAdapter
authenticated()
는 일치하는 URL이 액세스하기 전에 인증되어야 함을 의미합니다.
anonymous()
는 일치하는 URL에 익명으로 액세스할 수 있음을 의미합니다. 익명()으로 설정된 URL이 필터 체인
denyAll()
을 실행한다는 점을 제외하면 효과는 allowedAll()과 유사합니다. 이는 일치하는 URL이 허용되지 않음을 의미합니다. 액세스할 수 있습니다.
rememberMe()
"Remember Me" 사용자는 이 웹사이트에 접근할 수 있으며 이는 많은 웹사이트와 유사하며 10일 동안 로그인할 필요가 없습니다. 한 번 로그인하면 기억할 수 있으며, 이후에는 로그인할 필요가 없습니다. 🎜🎜🎜fullAuthenticated()
사용자는 나를 기억하지 않는 경우에만 액세스할 수 있습니다. 즉, 단계별로 로그인을 하셔야 합니다. 🎜🎜역할 권한 판단🎜🎜🎜🎜hasAuthority(String)
사용자에게 특정 권한이 있는지 여부를 결정합니다. 사용자의 권한은 사용자 정의 로그인 논리에 의해 결정됩니다🎜 🎜🎜hasAnyAuthority(String ...)
사용자에게 주어진 권한 중 하나가 있으면 액세스가 허용됩니다🎜🎜🎜hasRole(String)
사용자가 역할에 따라 액세스가 허용됩니다. 그렇지 않으면 403이 나타납니다🎜🎜🎜hasAnyRole(String ...)
사용자가 지정된 역할 중 하나를 가지고 있으면 액세스가 허용됩니다🎜🎜🎜hasIpAddress(String)
지정된 IP에 대한 요청인 경우 액세스를 실행합니다. request.getRemoteAddr()을 통해 IP 주소를 얻을 수 있습니다. 🎜🎜Spring Security🎜🎜Pom 파일을 인용하고 🎜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('ADMIN')") public String demo() { return "Welcome"; } @GetMapping("/user/list") @PreAuthorize("hasAnyRole('ADMIN','USER')") public String getUserList() { return "User List"; } @GetMapping("/article/list") @PreAuthorize("hasRole('ADMIN')") public String getArticleList() { return "Article List"; } }🎜를 추가하세요. 비밀번호는 실행 후 자동으로 생성됩니다. 기본 사용자 이름은 user입니다. 🎜🎜

Spring 보안 구성(시작하기)
🎜메모리에 두 개의 사용자 역할(관리자 및 사용자)을 구성하고(프로세스를 단순화하고 논리를 이해하기 위해) 🎜역할 액세스 권한을 설정합니다. 동시에 관리자는 모든 경로(예: /*)에 액세스할 수 있으며, 사용자는 /user 아래의 모든 경로에만 액세스할 수 있습니다. 🎜🎜구성 클래스를 사용자 정의하고WebSecurityConfigurerAdapter
인터페이스를 구현합니다. WebSecurityConfigurerAdapter
인터페이스에는 두 가지 구성() 메서드가 사용되며, 그 중 하나는 사용자 ID를 구성하고 다른 하나는 사용자를 구성합니다. 권한: 🎜🎜 사용자 ID를 구성하는 구성() 메서드: 🎜🎜SecurityConfig🎜rrreee🎜인터페이스 테스트 추가🎜rrreee🎜🎜🎜위 내용은 SpringBoot를 사용하는 방법 SpringSecurity의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.

java'stopfeaturessificeNificeLynitySteperformanceandscalibers

JVM의 핵심 구성 요소에는 클래스 로더, runtimedataarea 및 executionEngine이 포함됩니다. 1) 클래스 로더는 클래스 및 인터페이스로드, 연결 및 초기화를 담당합니다. 2) runtimedataarea에는 Methodarea, 힙, 스택, Pcregister 및 NativeMethodStacks가 포함되어 있습니다. 3) ExecutionEngine은 바이트 코드의 실행 및 최적화를 담당하는 통역사, JitCompiler 및 GarbageCollector로 구성됩니다.

Java'sSafetyandsecurityArebolsteredBy : 1) 강력한, reventStype relatedErrors; 2) AutomaticMemoryManagementViageGageCollection; 3) 샌드 박스, 고립 코드 프롬 시스템; 및 4) 강도 핸드 링, 보장

javaoffersseveralkeyfeaturestenhancecodingskills : 1) 객체 지향적 인 프로그래밍 allowsmodelingreal-worldentities, 예시적인 혈관 림 모르 즘 .2) 예외적 인 handlingprovidesrobusterrormanagement.3) LambdaexorsionssimplifyOperations, 개선

thejvmisacrucialcomponentsThrunsjavacodebacodebybacodebytranslatingitintintintincinomachine-specificinstructions, 영향력 성능, 보안 및 포트 가능성


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

드림위버 CS6
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는