1、springboot基礎項目搭建
1.1 新建maven項目
springboot-2.0-security
1.2 添加maven依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<!-- 管理依賴 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- SpringBoot整合Web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- springboot整合freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
<!-- 注意: 這裏必須要添加, 否者各種依賴有問題 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
1.3 配置文件添加
application.yml
# 配置freemarker
spring:
freemarker:
# 設置模板後綴名
suffix: .ftl
# 設置文檔類型
content-type: text/html
# 設置頁面編碼格式
charset: UTF-8
# 設置頁面緩存
cache: false
# 設置ftl文件路徑
template-loader-path:
- classpath:/templates
# 設置靜態文件路徑,js,css等
mvc:
static-path-pattern: /static/**
1.4 啓動類
AppSpringBootSecurity
package com.mine;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppSpringBootSecurity {
public static void main(String[] args) {
SpringApplication.run(AppSpringBootSecurity.class, args);
}
}
1.5 控制器
OrderController
package com.mine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class OrderController {
// 首頁
@RequestMapping("/")
public String index() {
return "index";
}
// 查詢訂單
@RequestMapping("/showOrder")
public String showOrder() {
return "showOrder";
}
// 添加訂單
@RequestMapping("/addOrder")
public String addOrder() {
return "addOrder";
}
// 修改訂單
@RequestMapping("/updateOrder")
public String updateOrder() {
return "updateOrder";
}
// 刪除訂單
@RequestMapping("/deleteOrder")
public String deleteOrder() {
return "deleteOrder";
}
// 自定義登陸頁面
@GetMapping("/login")
public String login() {
return "login";
}
}
ErrorController
package com.mine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ErrorController {
// 403權限不足頁面
@RequestMapping("/error/403")
public String error() {
return "/error/403";
}
}
1.6 頁面添加(src/main/resources/templates)
index.ftl
<h1>訂單系統</h1>
<br>
<a href="showOrder">查詢訂單</a>
<br>
<a href="addOrder">添加訂單</a>
<br>
<a href="deleteOrder">刪除訂單</a>
<br>
<a href="updateOrder">修改訂單</a>
addOrder.ftl
<h1>添加訂單</h1>
updateOrder.ftl
<h1>修改訂單</h1>
showOrder.ftl
<h1>查詢訂單</h1>
deleteOrder.ftl
<h1>刪除訂單</h1>
login.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>權限控制登陸系統</h1>
<form action="/login" method="post">
<span>用戶名稱</span><input type="text" name="username" /> <br>
<span>用戶密碼</span><input type="password" name="password" /> <br>
<input type="submit" value="登陸">
</form>
<#if RequestParameters['error']??>
用戶名稱或者密碼錯誤
</#if>
</body>
</html>
error/403.ftl
您的權限不足!
error/logFail.ftl
登陸失敗!
2、spring-security兩種認證模式
formLogin:表單認證
httpBasic:web瀏覽器與服務器認證
3、httpBasic認證模式(基於1搭建的springboot項目)
3.1 pom中引入依賴
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.2 添加SecurityConfig
package com.mine.config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("addOrder");
}
// 配置HttpSecurity 攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
}
}
3.3 運行啓動類-AppSpringBootSecurity
4、formLogin認證模式(基於1搭建的springboot項目)
4.1 pom中引入依賴
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
4.2 添加SecurityConfig
package com.mine.config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("addOrder");
}
// 配置HttpSecurity 攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
}
}
4.3 運行啓動類-AppSpringBootSecurity
4.4 配置用戶權限
admin:管理員賬號,擁有所有權限
query:只能查詢訂單
修改SecurityConfig
package com.mine.config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder", "addOrder", "updateOrder", "deleteOrder");
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("query")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder");
}
// 配置HttpSecurity 攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/showOrder").hasAuthority("showOrder")
.antMatchers("/addOrder").hasAuthority("addOrder")
.antMatchers("/updateOrder").hasAuthority("updateOrder")
.antMatchers("/deleteOrder").hasAuthority("deleteOrder")
.antMatchers("/**").fullyAuthenticated().and().formLogin();
}
}
4.4 修改錯誤頁面
4.4.1 添加ErrorPageAutoConfiguration
package com.mine.config;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
/**
*
* 自定義錯誤頁面
*
*/
@Configuration
public class ErrorPageAutoConfiguration {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
return factory;
}
}
4.5 自定義登錄頁面
4.5.1 修改SecurityConfig
package com.mine.config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder", "addOrder", "updateOrder", "deleteOrder");
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("query")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder");
}
// 配置HttpSecurity 攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/showOrder").hasAuthority("showOrder")
.antMatchers("/addOrder").hasAuthority("addOrder")
.antMatchers("/updateOrder").hasAuthority("updateOrder")
.antMatchers("/deleteOrder").hasAuthority("deleteOrder")
.antMatchers("/login").permitAll()
.antMatchers("/**").fullyAuthenticated().and().formLogin()
.loginPage("/login").and().csrf().disable();
}
}
4.6 登錄成功失敗
4.6.1 添加MyAuthenticationSuccessHandler
package com.mine.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
// 自定義登錄成功處理
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
System.out.println("登錄成功");
response.sendRedirect("/");
}
}
4.6.2 添加MyAuthenticationFailureHandler
package com.mine.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
// 自定義失敗處理器
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
System.out.println("登錄失敗");
response.sendRedirect("/logFail");
}
}
4.6.3 修改OrderController
package com.mine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class OrderController {
// 首頁
@RequestMapping("/")
public String index() {
return "index";
}
// 查詢訂單
@RequestMapping("/showOrder")
public String showOrder() {
return "showOrder";
}
// 添加訂單
@RequestMapping("/addOrder")
public String addOrder() {
return "addOrder";
}
// 修改訂單
@RequestMapping("/updateOrder")
public String updateOrder() {
return "updateOrder";
}
// 刪除訂單
@RequestMapping("/deleteOrder")
public String deleteOrder() {
return "deleteOrder";
}
// 自定義登陸頁面
@GetMapping("/login")
public String login() {
return "login";
}
// 自定義登陸失敗頁面
@RequestMapping("/logFail")
public String logFail() {
System.out.println("進入登錄失敗頁面");
return "error/logFail";
}
}
4.6.4 修改SecurityConfig
package com.mine.config;
import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.mine.handler.MyAuthenticationFailureHandler;
import com.mine.handler.MyAuthenticationSuccessHandler;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSuccessHandler successHandler;
@Autowired
private MyAuthenticationFailureHandler failureHandler;
// 用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder", "addOrder", "updateOrder", "deleteOrder");
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("query")
.password(new BCryptPasswordEncoder().encode("123456")).authorities("showOrder");
}
// 配置HttpSecurity 攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/showOrder").hasAuthority("showOrder")
.antMatchers("/addOrder").hasAuthority("addOrder")
.antMatchers("/updateOrder").hasAuthority("updateOrder")
.antMatchers("/deleteOrder").hasAuthority("deleteOrder")
.antMatchers("/login").permitAll()
.antMatchers("/logFail").permitAll()
.antMatchers("/**").fullyAuthenticated().and().formLogin().successHandler(successHandler).failureHandler(failureHandler)
.loginPage("/login").and().csrf().disable();
}
}