SpringSecurity如何實(shí)現(xiàn)配置單個(gè)HttpSecurity
一、創(chuàng)建項(xiàng)目并導(dǎo)入依賴
<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>
二、相關(guān)配置和代碼
在創(chuàng)建完項(xiàng)目時(shí),我們得springboot項(xiàng)目所有接口都被保護(hù)起來了,如果要想訪問必須登陸,用戶名默認(rèn)是user,密碼在項(xiàng)目啟動(dòng)時(shí)生成在控制臺(tái)。
1)我們可以設(shè)置自己得賬戶和密碼,有兩種方法配置
1.1)在application.properties中配置
spring.security.user.name=fernfei
spring.security.user.password=fernfei
spring.security.user.roles=admin
1.2)在配置類中配置
注:需要在配置類上加上@configuration注解
步驟1.2.1)
創(chuàng)建SecurityConfig繼承WebSecurityConfigurerAdpater
步驟1.2.2)
實(shí)現(xiàn)WebSecurityConfigurerAdpater中的configure(AuthenticationManagerBuilder auth)方法
步驟1.2.3)
從 Spring5 開始,強(qiáng)制要求密碼要加密,如果非不想加密,可 以使用一個(gè)過期的 PasswordEncoder 的實(shí)例
NoOpPasswordEncoder,但是不建議這么做,畢竟不安全。

這樣就算完成自己定義賬戶密碼了。
2)HttpSecurity配置
2.1)實(shí)現(xiàn)config(HttpSecurity http)方法
2.2)相關(guān)代碼
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/db/**").hasAnyRole("admin","user")
.antMatchers("/user/**").access("hasAnyRole('admin','user')")
//剩下的其他路徑請(qǐng)求驗(yàn)證之后就可以訪問
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/dologin")
.loginPage("/login")
.usernameParameter("uname")
.passwordParameter("pwd")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter pw = response.getWriter();
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", 200);
map.put("msg", authentication.getPrincipal());
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter pw = response.getWriter();
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", 401);
if (exception instanceof LockedException) {
map.put("msg", "賬戶被鎖定,登陸失??!");
} else if (exception instanceof BadCredentialsException) {
map.put("msg", "賬戶或者密碼錯(cuò)誤,登陸失??!");
} else if (exception instanceof DisabledException) {
map.put("msg", "賬戶被禁用,登陸失?。?);
} else if (exception instanceof AccountExpiredException) {
map.put("msg", "賬戶已過期,登陸失??!");
} else if (exception instanceof CredentialsExpiredException) {
map.put("msg", "密碼已過期,登陸失??!");
} else {
map.put("msg", "登陸失敗!");
}
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
}
})
.permitAll()
.and()
.csrf().disable();
}
2.3)代碼解釋
2.3.1)/admin/**路徑下的必須有admin角色才能訪問
.antMatchers("/admin/**").hasRole("admin")
2.3.2)/db/**和/user/**下的路徑,admin和user角色都可以訪問
.antMatchers("/db/**").hasAnyRole("admin","user")
.antMatchers("/user/**").access("hasAnyRole('admin','user')")
2.3.3)表示剩下的任何請(qǐng)求只要驗(yàn)證之后都可以訪問
.anyRequest().authenticated()
2.3.4)開啟表單登陸
.formLogin()
2.3.5)登陸處理的路徑
.loginProcessingUrl("/dologin")
2.3.6)登陸的頁面,如果不寫會(huì)使用默認(rèn)的登陸頁面
.loginPage("/login")
2.3.7)定義登錄時(shí),用戶名的 key,默認(rèn)為 username
.usernameParameter("uname")
2.3.7)定義登錄時(shí),用戶名的 key,默認(rèn)為 password
.passwordParameter("pwd")
2.3.8)登陸成功的處理(用于前后端分離時(shí),直接返回json
.successHandler()
紅框里面的類是存放登陸成功后的用戶信息

2.3.9)下圖就是登陸成功后直接返回url的方法

2.3.10)同上,登陸失敗的處理
.failureHandler()
判斷屬于哪個(gè)異常可以更友好給用戶作出提示
可以進(jìn)入這個(gè)類按Ctrl+H查看類的繼承關(guān)系,方便更好使用


2.3.11)permitALL()表示放開和登陸有關(guān)的接口,csrf是關(guān)閉csrf,以便我們?cè)?postman類似的軟件測(cè)試被系統(tǒng)給攔截了
.permitAll()
.and()
.csrf().disable();
3)controller層設(shè)置一些接口以便我們測(cè)試

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java SpringSecurity+JWT實(shí)現(xiàn)登錄認(rèn)證
這篇文章主要介紹了Java SpringSecurity+JWT實(shí)現(xiàn)登錄認(rèn)證,首先通過給需要登錄認(rèn)證的模塊添加mall-security依賴展開介紹,感興趣的朋友可以參考一下2022-06-06
java.lang.OutOfMemoryError 錯(cuò)誤整理及解決辦法
這篇文章主要介紹了java.lang.OutOfMemoryError 錯(cuò)誤整理及解決辦法的相關(guān)資料,需要的朋友可以參考下2016-10-10
Java通過apache poi生成excel實(shí)例代碼
本篇文章主要介紹了Java通過apache poi生成excel實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
Mybatis update數(shù)據(jù)庫死鎖之獲取數(shù)據(jù)庫連接池等待
這篇文章主要介紹了Mybatis update數(shù)據(jù)庫死鎖之獲取數(shù)據(jù)庫連接池等待的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07
httpclient connect連接請(qǐng)求方法源碼解讀
這篇文章主要為大家介紹了httpclient connect連接請(qǐng)求方法解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
最優(yōu)雅地整合 Spring & Spring MVC & MyBatis 搭建 Java 企業(yè)級(jí)應(yīng)用(附源碼)
這篇文章主要介紹了最優(yōu)雅地整合 Spring & Spring MVC & MyBatis 搭建 Java 企業(yè)級(jí)應(yīng)用(附源碼),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
Java多線程并發(fā)執(zhí)行demo代碼實(shí)例
這篇文章主要介紹了Java多線程并發(fā)執(zhí)行demo代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06

