一.Spring Security快速??
1.添加security啟動器
<!-- Spring Security 提供的安全管理依賴啟動器 --><dependency><groupId> org.springframework.boot </groupId><artifactId> spring-boot-starter-security </artifactId></dependency>
項(xiàng)?啟動測試
?這種默認(rèn)安全管理?式存在諸多問題。例如,只有唯?的默認(rèn)登錄?戶user,密碼隨機(jī)?成且過于暴露、登錄?? 及錯(cuò)誤提示??不是我們想要的等。
1.MVC Security安全配置介紹
1.下?我們通過Spring Security API查看WebSecurityConfigurerAdapter的主要?法,具體如下表
@EnableWebSecurity // 開啟MVC Security安全?持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//定制基于HTTP請求的?戶訪問控制
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
//定制?戶認(rèn)證管理器來實(shí)現(xiàn)?戶認(rèn)證
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
}
?4 ?定義?戶認(rèn)證
????????1.In-Memory Authentication:內(nèi)存身份認(rèn)證
????????2.JDBC Authentication:JDBC身份認(rèn)證
????????3.UserDetailsService:身份詳情服務(wù)
????????4.LDAP Authentication:LDAP身份認(rèn)證
????????5.AuthenticationProvider:身份認(rèn)證提供商
4.1.2 使?內(nèi)存進(jìn)?身份認(rèn)證? ?寫一個(gè)配置類即可
package com.cy.config;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationMa
nagerBuilder;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerA
dapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* MVC Security管理配置的?定義WebSecurityConfigurerAdapter類
*/
@EnableWebSecurity // 開啟MVC Security安全?持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/** ?戶身份認(rèn)證?定義配置 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 密碼需要設(shè)置編碼器
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// 1.使?內(nèi)存?戶信息,作為測試使?(設(shè)置?戶名、密碼和??)
auth.inMemoryAuthentication().passwordEncoder(encoder)
.withUser("tom").password(encoder.encode("123456")).roles("common")
.and()
.withUser("李四").password(encoder.encode("123456")).roles("vip");
}
}
4.3?UserDetailsService身份認(rèn)證
1.1.在項(xiàng)?的pom.xml?件中添加Mybaits依賴啟動器和lombok依賴。
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency><dependency><groupId> org.projectlombok </groupId><artifactId> lombok </artifactId></dependency>
package com.example.demo.service.imp;
import com.example.demo.pojo.Authority;
import com.example.demo.pojo.Customer;
import com.example.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/** ?定義?個(gè)UserDetailsService接?實(shí)現(xiàn)類進(jìn)??戶認(rèn)證信息封裝 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
/* 內(nèi)有提供自定義用戶查詢和權(quán)限查詢的方法
* getCustomer 根據(jù)名字查詢用戶信息 的方法
*
* getCustomerAuthority 根據(jù)名字查詢用戶權(quán)限 的方法
* */
private CustomerService customerService;
@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
// 通過業(yè)務(wù)?法獲取?戶及權(quán)限信息
Customer customer = customerService.getCustomer(username);
List<Authority> authorities = customerService.getCustomerAuthority(username);
// 對?戶權(quán)限進(jìn)?封裝
List<SimpleGrantedAuthority> list = authorities.stream().map(authority -> new
SimpleGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
// 返回封裝的UserDetails?戶詳情類
if (customer != null) {
UserDetails userDetails = new User(customer.getUsername(),
customer.getPassword(), list);
return userDetails;
} else {
// 如果查詢的?戶不存在(?戶名不存在),必須拋出此異常
throw new UsernameNotFoundException("當(dāng)前?戶不存在!");
}}}
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import javax.sql.DataSource;
import java.util.Date;
import java.util.HashMap;
//開啟安全管理的支持
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired //Hikari連接池,自動將mysql配置信息加載連接池對象上
private DataSource dataSource;
//1.用戶身份認(rèn)證的配置
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // 開啟基于HttpServletRequest請求訪問的限制
.antMatchers("/").permitAll() // 開啟Ant?格的路徑匹配。?條件對請求進(jìn)?放?
.antMatchers("/login/**").permitAll()
.antMatchers("/detail/common/**").hasRole("common") // 匹配?戶是否有某?個(gè)??
.antMatchers("/detail/vip/**").hasRole("vip")
.anyRequest().authenticated()// 匹配任何請求。匹配已經(jīng)登錄認(rèn)證的?戶
.and() // 功能連接符
.formLogin(); // 開啟基于表單的?戶登錄
http.formLogin() // 開啟基于表單的?戶登錄
// ?戶登錄??跳轉(zhuǎn)路徑,默認(rèn)為get請求的/login。?條件對請求進(jìn)?放?
.loginPage("/userLogin").permitAll()
.usernameParameter("name") // 登錄?戶的?戶名參數(shù), 默認(rèn)為username
.passwordParameter("pwd") // 登錄?戶的密碼參數(shù),默認(rèn)為password
.defaultSuccessUrl("/") // ?戶直接登錄后默認(rèn)跳轉(zhuǎn)地址
.failureUrl("/userLogin?error"); // ?戶登錄失敗后的跳轉(zhuǎn)地址,默認(rèn)為/login?erro
// ?定義?戶退出控制
http.logout()
.logoutUrl("/mylogout")
.logoutSuccessUrl("/");
// 定制Remember-me記住我功能
http.rememberMe()
.rememberMeParameter("rememberme")
.tokenValiditySeconds(200)
// 對Cookie信息進(jìn)?持久化管理
.tokenRepository(tokenRepository());
}
@Bean
/** 持久化Token存儲 */
public JdbcTokenRepositoryImpl tokenRepository() {
JdbcTokenRepositoryImpl jti = new JdbcTokenRepositoryImpl();
jti.setDataSource(dataSource);
//自動創(chuàng)建數(shù)據(jù)庫表字段
jti.setCreateTableOnStartup(true);
return jti;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 密碼需要設(shè)置編碼器
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
}
完成以上配置基于內(nèi)存進(jìn)?身份認(rèn)證? 就結(jié)束了
接下來是配置的信息文章來源:http://www.zghlxwxcb.cn/news/detail-742168.html
方法 | 描述 |
---|---|
authorizeRequests() | 開啟基于HttpServletRequest請求訪問的限制 |
formLogin() | 開啟基于表單的?戶登錄 |
httpBasic() | 開啟基于HTTP請求的Basic認(rèn)證登錄 |
logout() | 開啟退出登錄的?持 |
sessionManagement() | 開啟Session管理配置 |
rememberMe() | 開啟記住我功能 |
csrf() | 配置CSRF跨站請求偽造防護(hù)功能 |
?法
|
描述
|
---|---|
antMatchers(java.lang.String... antPtterns)
|
開啟
Ant
?格的路徑匹配
|
mvcMatchers(java.lang.String... patterns)
|
開啟
MVC
?格的路徑匹配(與
Ant
?格類似)
|
regexMatchers(java.lang.Sring...
regexPatterns)
|
開啟正則表達(dá)式的路徑匹配
|
and()
|
功能連接符
|
anyRequest()
|
匹配任何請求
|
rememberMe()
|
開啟記住我功能
|
access(String attribute)
|
匹配給定的
SpEL
表達(dá)式計(jì)算結(jié)果是否為
true
|
hasAnyRole(String... roles)
|
匹配?戶是否有參數(shù)中的任意??
|
hasRole(Sring role)
|
匹配?戶是否有某?個(gè)??
|
hasAnyAuthority(String... authorities)
|
匹配?戶是否有參數(shù)中的任意權(quán)限
|
hasAuthority(String authority)
|
匹配?戶是否有某?個(gè)權(quán)限
|
authenticated()
|
匹配已經(jīng)登錄認(rèn)證的?戶
|
fullyAuthenticated()
|
匹配完整登錄認(rèn)證的?戶(?
rememberMe
登錄? 戶)
|
hasIpAddress(String ipAddressExpression)
|
匹配某
IP
地址的訪問請求
|
permitAll()
|
?條件對請求進(jìn)?放?
|
?法
|
描述
|
---|---|
loginPage(String loginPage)
|
?戶登錄??跳轉(zhuǎn)路徑,默認(rèn)為
get
請 求的/login
|
successForwardUrl(String forwardUrl)
|
?戶登錄成功后的重定向地址
|
successHandler(AuthenticationSuccessHandler
authenticationSuccessHandler)
|
?戶登錄成功后的處理
|
defaultSuccessUrl(String defaultSuccessUrl)
|
?戶直接登錄后默認(rèn)跳轉(zhuǎn)地址
|
failureForwardUrl(String forwardUrl)
|
?戶登錄失敗后的重定向地址
|
failureUrl(String authenticationFailureUrl)
|
?戶登錄失敗后的跳轉(zhuǎn)地址,默認(rèn)
為
/login?error
|
failureHandler(AuthenticationFailureHandler
authenticationFailureHandler)
|
?戶登錄失敗后的錯(cuò)誤處理
|
usernameParameter(String usernameParameter)
|
登錄?戶的?戶名參數(shù), 默認(rèn)為
username
|
passwordParameter(String passwordParameter)
|
登錄?戶的密碼參數(shù),默認(rèn)為
password
|
loginProcessingUrl(String loginProcessingUrl)
|
登錄表單提交的路徑,默認(rèn)為
post
請
求的
/login
|
permitAll()
|
permitAll()
?條件對請求進(jìn)?放?
|
?法
|
描述
|
---|---|
rememberMeParameter(String rememberMeParameter)
|
指示在登錄時(shí)記住?戶的
HTTP
參數(shù)
|
key(String key)
|
記住我認(rèn)證?成的
Token
令牌標(biāo)識
|
tokenValiditySeconds(int tokenValiditySeconds)
|
記住我
Token
令牌有效期,單位為秒
|
tokenRepository(PersistentTokenRepository
tokenRepository)
|
指定要使?的
PersistentTokenRepository
,?來配置持久化
Token
令牌
|
alwaysRemember(boolean alwaysRemember)
|
是否應(yīng)該始終創(chuàng)建記住我
Cookie
,默認(rèn)為
false
|
clearAuthentication(boolean clearAuthentication)
|
是否設(shè)置
Cookie
為安全的,如果設(shè)置為
true
,則必須通過
HTTPS
進(jìn)?連接請 求
|
?法
|
描述
|
---|---|
disable()
|
關(guān)閉
Security
默認(rèn)開啟的
CSRF
防御功能
|
csrfTokenRepository(CsrfTokenRepository
csrfTokenRepository)
|
指定要使?的
CsrfTokenRepository
(
Token
令牌持久化倉庫)。默認(rèn)是由
LazyCsrfTokenRepository
包裝的
HttpSessionCsrfTokenRepository
|
requireCsrfProtectionMatcher(RequestMatcher
requireCsrfProtectionMatcher)
|
指定針對什么類型的請求應(yīng)?
CSRF
防護(hù)功能。默認(rèn)設(shè)置是忽略
GET
、
HEAD
、
TRACE
和
OPTIONS
請
求,?處理并防御其他所有請求
|
以上就是一些比較常用的配置信息文章來源地址http://www.zghlxwxcb.cn/news/detail-742168.html
到了這里,關(guān)于Spring Boot安全管理的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!