概述
Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于 Spring 的应用程序的事实上的标准。
Spring Security 是一个专注于为 Java 应用程序提供身份验证和授权的框架。与所有 Spring 项目一样,Spring Security 的真正强大之处在于它可以轻松扩展以满足自定义要求
特性:
-对身份验证和授权的全面且可扩展的支持
-防止会话固定、点击劫持、跨站点请求伪造等攻击
-Servlet API 集成
-与 Spring Web MVC 的可选集成
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置类:SecurityConfig 要继承 WebSecurityConfigurerAdapter
import com.had.case_security.service.CustomUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @Description:
* @Author had
* @Date 2021/09/02
*/
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;
/**
* 自定义认证策略
*
* @return
*/
@Autowired
public void configGlobal(AuthenticationManagerBuilder auth) throws Exception {
String password = passwordEncoder().encode("123456");
log.info("加密后的密码:" + password);
auth.inMemoryAuthentication().withUser("admin").password(password)
.roles("ADMIN").and();
auth.inMemoryAuthentication().withUser("user").password(password)
.roles("USER").and();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/500").permitAll()
.antMatchers("/403").permitAll()
.antMatchers("/404").permitAll()
.anyRequest() //任何其它请求
.authenticated() //都需要身份认证
.and()
.formLogin() //使用表单认证方式
.loginProcessingUrl("/login")//配置默认登录入口
.and()
.csrf().disable();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
controller:
package com.had.case_security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Author had
* @Date 2021/09/02
*/
@Controller
public class HelloController {
@GetMapping("/403")
public String accessError() {
return "403";
}
@GetMapping("/404")
public String notFoundPage() {
return "404";
}
@GetMapping("/500")
public String internalError() {
return "500";
}
}
错误页面结构:
application.yml:
server:
port: 9003
#thymeleaf模版前缀
spring:
thymeleaf:
prefix: classpath:/templates/
页面测试:
启动后会看到打印加密后的密码,但是我们在表单输入的还是123456