網(wǎng)絡(luò)裝修公司長(zhǎng)春做網(wǎng)絡(luò)優(yōu)化的公司
?Spring Boot整合
1、RBAC
?權(quán)限模型
RBAC模型(Role-Based Access Control:基于角色的訪問控制)
在RBAC模型里面,有3個(gè)基礎(chǔ)組成部分,分別是:用戶、角色和權(quán)限,它們之間的關(guān)系如下圖所示
SELECT * FROM sec_permission;
SELECT * FROM sec_role_permission ;
SELECT * FROM sec_role;
SELECT * FROM sec_user_role;
SELECT * FROM sec_user;
2、啟動(dòng)器依賴引入
啥配置也沒做,啥類也沒寫。只是增加了一個(gè)啟動(dòng)器依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
重新訪問首頁:http://localhost:8080/
3、用戶名密碼
默認(rèn):
用戶名默認(rèn):user
密碼在服務(wù)啟動(dòng)時(shí)打印在了控制臺(tái)
自定義:
?當(dāng)然我們也可以通過application.yml指定配置用戶名密碼
security.user.name 指定默認(rèn)的用戶名,默認(rèn)為user.
security.user.password 默認(rèn)的用戶密碼.
spring:security:user:name: adminpassword: admin
關(guān)閉security驗(yàn)證:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();//配置不需要登錄驗(yàn)證} }
WebSecurityConfigurerAdapter?是由Spring Security提供的Web應(yīng)用安全配置的適配器
WebSecurityConfigurerAdapter
?是一個(gè)適配器類,允許開發(fā)者通過重寫特定的方法來自定義其 Web 安全配置
創(chuàng)建一個(gè)配置類WebSecurityConfig
繼承WebSecurityConfigurerAdapter
這個(gè)抽象類并重寫configure(HttpSecurity http)
方法,可以精確地定義哪些URL可以由哪些角色訪問。
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() // 表單方式.and().authorizeRequests() // 授權(quán)配置.anyRequest().authenticated(); //所有未匹配的請(qǐng)求都需要用戶進(jìn)行身份驗(yàn)證}
}
Spring Security提供了這種鏈?zhǔn)降姆椒ㄕ{(diào)用。上面配置指定了認(rèn)證方式為表單登錄,并且所有請(qǐng)求都需要進(jìn)行認(rèn)證。
HttpSecurity
?是 Spring Security 中用于構(gòu)建安全配置的一個(gè)類。通過該類,開發(fā)者可以配置許多與 HTTP 安全相關(guān)的選項(xiàng),如認(rèn)證、授權(quán)、CORS、CSRF 保護(hù)等
.formLogin()
?是?HttpSecurity
?類的一個(gè)方法,用于啟用基于表單的身份驗(yàn)證。當(dāng)你調(diào)用這個(gè)方法時(shí),Spring Security 會(huì)自動(dòng)配置登錄表單的相關(guān)設(shè)置,如登錄頁面的 URL、登錄成功和失敗的處理等。你可以進(jìn)一步定制這些設(shè)置,以適應(yīng)你的應(yīng)用程序需求。-------------------------------
http.authorizeRequests()
?是?HttpSecurity
?類的一個(gè)方法,用于定義 URL 的訪問權(quán)限。通過該方法,你可以指定哪些 URL 需要特定的角色或權(quán)限才能訪問,哪些 URL 可以公開訪問等。--------------
.anyRequest().authenticated()
?表示所有未匹配的請(qǐng)求都需要用戶進(jìn)行身份驗(yàn)證。
4、基于數(shù)據(jù)庫(kù)的登錄認(rèn)證
Spring Security支持通過實(shí)現(xiàn)UserDetailsService接口的方式來提供用戶認(rèn)證授權(quán)信息。主要功能:根據(jù)用戶名查詢用戶信息
@Service
public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate UserDao userDao;@Autowiredprivate RoleDao roleDao;@Autowiredprivate PermissionDao permissionDao;@Resourceprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//通過用戶名從數(shù)據(jù)庫(kù)獲取用戶信息User user = userDao.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("未找到用戶信息 : " + username));//定義權(quán)限列表List<GrantedAuthority> authorities = new ArrayList<>();authorities.add(new SimpleGrantedAuthority("a"));authorities.add(new SimpleGrantedAuthority("b"));authorities.add(new SimpleGrantedAuthority("c"));//返回spring security的User對(duì)象//user.getPassword() 數(shù)據(jù)庫(kù)中的密碼已經(jīng)是密文存儲(chǔ)return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);}
}
返回值類型是UserDetails
,我們可以直接使用Spring Security提供的UserDetails
接口實(shí)現(xiàn)類org.springframework.security.core.userdetails.User
5、授權(quán)GrantedAuthority
GrantedAuthority
則表示用戶驗(yàn)證通過后被授予的權(quán)限。
SimpleGrantedAuthority
SimpleGrantedAuthority
是默認(rèn)的授權(quán)實(shí)現(xiàn),它只存儲(chǔ)權(quán)限(存儲(chǔ)授予Authentication
對(duì)象的權(quán)限的String
表示形式),是一種簡(jiǎn)易的授權(quán)實(shí)現(xiàn)。
GrantedAuthority:直譯"授予權(quán)限"
Authentication:直譯"驗(yàn)證"
給我的感覺就是權(quán)限就是一個(gè)字符串,難道什么樣的字符串都行嗎?為啥定義的這么模糊
那我們就姑且給他"a","b","c"。??纯此趺凑f
AuthorityUtils:此類一般用于UserDetailsService的實(shí)現(xiàn)類中的loadUserByUsername方法
作用為給user賬戶添加一個(gè)或多個(gè)權(quán)限,用逗號(hào)分隔,底層調(diào)用的是createAuthorityList方法,唯一區(qū)別在于此方法把所有的權(quán)限包含進(jìn)一個(gè)字符串參數(shù)中,只不過用逗號(hào)分隔。
@Service public class UserDetailsServiceImpl implements UserDetailsService{@AutowiredPasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//比較密碼String pass=passwordEncoder.encode("123");//加密return new User(username,pass,AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));}}
createAuthorityList
將權(quán)限轉(zhuǎn)換為L(zhǎng)ist,如
@Service public class UserDetailsServiceImpl implements UserDetailsService{@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {List<GrantedAuthority> list=AuthorityUtils.createAuthorityList("admin","normal");//一個(gè)權(quán)限一個(gè)參數(shù)return new User(username,pass,list);} }
1
6、配置類中配置
實(shí)際項(xiàng)目中我們不會(huì)把密碼明文存儲(chǔ)在數(shù)據(jù)庫(kù)中。只需要使用把BCryptPasswordEncoder對(duì)象注入Spring容器中,SpringSecurity就會(huì)使用該P(yáng)asswordEncoder來進(jìn)行密碼校驗(yàn)
Spring Security實(shí)現(xiàn)的BCryptPasswordEncoder
已經(jīng)足夠強(qiáng)大,它對(duì)相同的密碼進(jìn)行加密后可以生成不同的結(jié)果
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Resourceprivate UserDetailsService userDetailsService;@Beanpublic PasswordEncoder passwordEncoder() {//使用默認(rèn)的BCryptPasswordEncoder加密方案return new BCryptPasswordEncoder();}/*** 配置用戶詳細(xì)信息的服務(wù)和密碼編碼器** @param auth* @throws Exception*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//數(shù)據(jù)庫(kù)讀取的用戶進(jìn)行身份認(rèn)證auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() // 表單方式.and().authorizeRequests() // 授權(quán)配置.anyRequest().authenticated(); //所有未匹配的請(qǐng)求都需要用戶進(jìn)行身份驗(yàn)證}
}
Spring Security中的BCryptPasswordEncoder方法采用SHA-256 +隨機(jī)鹽+密鑰對(duì)密碼進(jìn)行加密。SHA系列是Hash算法,不是加密算法,使用加密算法意味著可以解密(這個(gè)與編碼/解碼一樣),但是采用Hash處理,其過程是不可逆的。
1)加密(encode):注冊(cè)用戶時(shí),使用SHA-256+隨機(jī)鹽+密鑰把用戶輸入的密碼進(jìn)行hash處理,得到密碼的hash值,然后將其存入數(shù)據(jù)庫(kù)中。
2)密碼匹配(matches):用戶登錄時(shí),密碼匹配階段并沒有進(jìn)行密碼解密(因?yàn)槊艽a經(jīng)過Hash處理,是不可逆的),而是使用相同的算法把用戶輸入的密碼進(jìn)行hash處理,得到密碼的hash值,然后將其與從數(shù)據(jù)庫(kù)中查詢到的密碼hash值進(jìn)行比較。如果兩者相同,說明用戶輸入的密碼正確。
再次訪問接口:http://127.0.0.1:8089/hello
使用賬號(hào)密碼登錄 admin/123456
Spring Security OAuth2
1、什么是OAuth
OAuth是一種用來規(guī)范令牌(Token)發(fā)放的授權(quán)機(jī)制,主要包含了四種授權(quán)模式:授權(quán)碼模式、簡(jiǎn)化模式、密碼模式和客戶端模式
OAuth相關(guān)的名詞
-
Third-party application?第三方應(yīng)用程序,比如這里的虎牙直播;
-
HTTP service?HTTP服務(wù)提供商,比如這里的QQ(騰訊);
-
Resource Owner?資源所有者,就是QQ的所有人,你;
-
User Agent?用戶代理,這里指瀏覽器;
-
Authorization server?認(rèn)證服務(wù)器,這里指QQ提供的第三方登錄服務(wù);
-
Resource server?資源服務(wù)器,這里指虎牙直播提供的服務(wù),比如高清直播,彈幕發(fā)送等(需要認(rèn)證后才能使用)。
Spring Security OAuth2主要包含認(rèn)證服務(wù)器和資源服務(wù)器這兩大塊的實(shí)現(xiàn):
認(rèn)證服務(wù)器主要包含了四種授權(quán)模式的實(shí)現(xiàn)和Token的生成與存儲(chǔ)
資源服務(wù)器主要是在Spring Security的過濾器鏈上加了OAuth2AuthenticationProcessingFilter過濾器,即使用OAuth2協(xié)議發(fā)放令牌認(rèn)證的方式來保護(hù)我們的資源
2、認(rèn)證授權(quán)服務(wù)器
創(chuàng)建認(rèn)證服務(wù)器很簡(jiǎn)單,只需要在Spring Security的配置類上使用@EnableAuthorizationServer
注解標(biāo)注即可
使用?
@EnableAuthorizationServer
?注解,在應(yīng)用中自動(dòng)開啟和配置 Spring Security OAuth 的授權(quán)服務(wù)組件。?
@EnableAuthorizationServer
?注解主要是導(dǎo)入兩個(gè)配置類,分別是:
AuthorizationServerEndpointsConfiguration
,這個(gè)配置類主要配置授權(quán)端點(diǎn),獲取token的端點(diǎn)。大家就把對(duì)應(yīng)的端點(diǎn)想象成controller即可,在這個(gè)controller下開放了若干個(gè)@RequestMapping,比如常見的有:/oauth/authorize(授權(quán)路徑)
,/oauth/token(獲取token)
等AuthorizationServerSecurityConfiguration
,主要是做spring-security的安全配置
3、資源服務(wù)器
資源服務(wù)器的配置也很簡(jiǎn)單,只需要在配置類上使用@EnableResourceServer
注解標(biāo)注即可:
通過資源服務(wù)器來保護(hù)我們指定的資源,必須在獲取授權(quán)認(rèn)證的時(shí)候才能訪問。在SpringBoot當(dāng)中,我們可以通過@EnableResourceServer
注解來開啟此功能。
@Configuration@EnableResourceServerpublic class ResourceConfigure extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests().antMatchers("/free/**").permitAll().and().authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();//必須認(rèn)證過后才可以訪問}}