【笔记】springboot+spring security登录流程实现
在登錄控制器中添加一個登錄接口login,在其中驗證驗證碼、用戶名、密碼信息。匹配成功之后,執行Spring Security的登錄認證機制。登錄成功之后,返回Token令牌憑證。
SysLoginController
(1)將用戶名密碼的認證信息封裝到JwtAuthenticatioToken對象。
(2)通過調用authenticationManager.authenticate(token)執行認證流程。
(3)通過SecurityContextHolder將認證信息保存到Security上下文。
(4)通過JwtTokenUtils.generateToken(authentication)生成token并返回。
serializable接口的作用:1、存儲對象在存儲介質中,以便在下次使用的時候,可以很快捷的重建一個副本;2、便于數據傳輸,尤其是在遠程調用的時候
Serializable接口是啟用其序列化功能的接口。實現java.io.Serializable 接口的類是可序列化的。沒有實現此接口的類將不能使它們的任意狀態被序列化或逆序列化
Spring Security 應用級別的安全主要包含兩個主要部分,即登錄認證(Authentication)和訪問授權(Authorization),首先用戶登錄的時候傳入登錄信息,登錄驗證器完成登錄認證并將登錄認證好的信息存儲到請求上下文,然后在進行其他操作,如接口訪問、方法調用時,權限認證器從上下文中獲取登錄認證信息,然后根據認證信息獲取權限信息,通過權限信息和特定的授權策略決定是否授權。
spring secuirty:
https://www.cnblogs.com/xifengxiaoma/p/10020960.html
Spring Security的登錄認證過程是委托給 AuthenticationManager 完成的,它先是解析出用戶名和密碼,然后把用戶名和密碼封裝到一個UsernamePasswordAuthenticationToken 中,傳遞給 AuthenticationManager,交由 AuthenticationManager 完成實際的登錄認證過程
spring security的關鍵配置:
安全配置類
下面這個配置類是Spring Security的關鍵配置。
在這個配置類中,我們主要做了以下幾個配置:
訪問路徑URL的授權策略,如登錄、Swagger訪問免登錄認證等
指定了登錄認證流程過濾器 JwtLoginFilter,由它來觸發登錄認證
指定了自定義身份認證組件 JwtAuthenticationProvider,并注入 UserDetailsService
指定了訪問控制過濾器 JwtAuthenticationFilter,在授權時解析令牌和設置登錄狀態
指定了退出登錄處理器,因為是前后端分離,防止內置的登錄處理器在后臺進行跳轉
WebSecurityConfig.java
package com.louis.springboot.spring.security.config;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;import com.louis.springboot.spring.security.security.JwtAuthenticationFilter; import com.louis.springboot.spring.security.security.JwtAuthenticationProvider; import com.louis.springboot.spring.security.security.JwtLoginFilter;/*** Security Config* @author Louis* @date Nov 28, 2018*/ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overridepublic void configure(AuthenticationManagerBuilder auth) throws Exception {// 使用自定義登錄身份認證組件auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService));}@Overrideprotected void configure(HttpSecurity http) throws Exception {// 禁用 csrf, 由于使用的是JWT,我們這里不需要csrfhttp.cors().and().csrf().disable().authorizeRequests()// 跨域預檢請求.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()// 登錄URL.antMatchers("/login").permitAll()// swagger.antMatchers("/swagger-ui.html").permitAll().antMatchers("/swagger-resources").permitAll().antMatchers("/v2/api-docs").permitAll().antMatchers("/webjars/springfox-swagger-ui/**").permitAll()// 其他所有請求需要身份認證.anyRequest().authenticated();// 退出登錄處理器http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());// 開啟登錄認證流程過濾器http.addFilterBefore(new JwtLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);// 訪問控制時登錄狀態檢查過濾器http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);}@Bean@Overridepublic AuthenticationManager authenticationManager() throws Exception {return super.authenticationManager();}}實例(自己配置固定的用戶名和密碼)
//Spring Security為Web應用提供了一個適配器類WebSecurityConfigurerAdapter, // 該類實現了WebSecurityConfigurer <WebSecurity>接口,并提供了兩個configure方法用于認證和授權操作。 開發者創建自己的Spring Security適配器類是非常簡單的, // 只需定義一個繼承WebSecurityConfigurerAdapter的類,并在該類中使用@Configuration注解, // 就可以通過重寫兩個configure方法來配置所需要的安全配置。自@Configuration public class SecutiryConfig extends WebSecurityConfigurerAdapter {//Spring Security為Web應用提供了一個適配器類WebSecurityConfigurerAdapter,// 該類實現了WebSecurityConfigurer <WebSecurity>接口,并提供了兩個configure方法用于認證和授權操作。// 開發者創建自己的Spring Security適配器類是非常簡單的,// 只需定義一個繼承WebSecurityConfigurerAdapter的類,// 并在該類中使用@Configuration注解,// 就可以通過重寫兩個configure方法來配置所需要的安全配置。 @Override public void configure(AuthenticationManagerBuilder auth) throws Exception{BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();String password = passwordEncoder.encode("123");auth.inMemoryAuthentication().withUser("root").password(password).roles("admin"); //如果沒有寫.roles,會報錯Cannot pass a null GrantedAuthority collection }@BeanPasswordEncoder getPasswordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception{http.formLogin()//這句表示自定義自己的登陸界面.loginPage("/login.html")//登錄頁面設置.loginProcessingUrl("/user") //登錄訪問路徑.defaultSuccessUrl("/test").permitAll() //表示登陸成功后要跳轉到的路徑.and().authorizeRequests().antMatchers("/","/test/hello").permitAll()//這個用來設置哪些路徑可以直接訪問,不需要認證.anyRequest().authenticated().and().csrf().disable();}}:
創建html:
controller:
@RestController public class jpaUserController {@GetMapping("test")public String index(){return "hello index";}}//在實際應用中,可以查詢數據庫獲取用戶和權限, // 這時需要自定義實現userdetails.UserDetailsService接口的類, // 并重寫public UserDetails loadUserByUsername(String username)方法 // 查詢對應的用戶和權限。:
輸入root 123
總結
以上是生活随笔為你收集整理的【笔记】springboot+spring security登录流程实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【学习笔记】比较分别用prim和krus
- 下一篇: 【算法】深度优先搜索遍历的应用 设计算法