網站首頁 編程語言 正文
自定義UsernamePasswordAuthenticationFilter
package com.monkeylessey.xp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* @author xp
* @version 1.0
* @date 2022/3/31 0031 17:13
*/
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// post請求
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map<String, Object> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = (String) map.get(getUsernameParameter());
String password = (String) map.get(getPasswordParameter());
username = (username != null) ? username : "";
username = username.trim();
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, token);
return this.getAuthenticationManager().authenticate(token);
} catch (IOException e) {
e.printStackTrace();
}
}
return super.attemptAuthentication(request,response);
}
}
Security配置類:
package com.monkeylessey.xp.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.monkeylessey.xp.MyUsernamePasswordAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author xp
* @version 1.0
* @date 2022/3/31 0031 17:52
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService getUserDetails() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(User.withUsername("xp").password("{noop}666").roles("admin").build());
return inMemoryUserDetailsManager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(getUserDetails());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* 自定義認證過濾器
* @return
* @throws Exception
*/
@Bean
public MyUsernamePasswordAuthenticationFilter get() throws Exception {
MyUsernamePasswordAuthenticationFilter myLoginFilter = new MyUsernamePasswordAuthenticationFilter();
myLoginFilter.setUsernameParameter("u");
myLoginFilter.setPasswordParameter("p");
myLoginFilter.setFilterProcessesUrl("/xplogin"); // 指定認證的請求
myLoginFilter.setAuthenticationManager(authenticationManagerBean());
myLoginFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
Map<String,Object> map = new HashMap<>();
map.put("msg", "登錄成功");
String s = new ObjectMapper().writeValueAsString(map);
response.getWriter().print(s);
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.OK.value());
System.out.println("認證失敗");
}
});
myLoginFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String,Object> map = new HashMap<>();
map.put("msg", "登錄失敗");
String s = new ObjectMapper().writeValueAsString(map);
response.getWriter().print(s);
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.FORBIDDEN.value());
System.out.println("認證失敗");
}
});
return myLoginFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin();
http.authorizeRequests()
.anyRequest().authenticated();
http.csrf().disable();
// at是用filter去替換某個filter
http.addFilterAt(get(), UsernamePasswordAuthenticationFilter.class);
}
}
測試接口
package com.monkeylessey.xp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xp
* @version 1.0
* @date 2022/3/31 0031 15:06
*/
@RestController
@RequestMapping
public class TestController {
@GetMapping("/one")
public String testA() {
return "小老弟你來啦";
}
}
隨手一個依賴吧
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
原理待更新。。。
原文鏈接:https://blog.csdn.net/qq_42682745/article/details/123930548
相關推薦
- 2022-11-17 Python+OpenCV之圖像輪廓詳解_python
- 2022-04-02 python3?QT5?端口轉發工具兩種場景分析_python
- 2022-03-22 .NET?6開發TodoList開發查詢分頁_實用技巧
- 2022-07-13 Docker技術_Docker與傳統虛擬機以及傳統容器的差異
- 2024-01-31 1273 - Unknown collation: ‘utf8mb4_0900_ai_ci‘, Ti
- 2022-10-21 使用react+redux實現彈出框案例_React
- 2022-08-14 python?中的@property的用法詳解_python
- 2022-07-29 pytest解讀fixture有效性及跨文件共享fixtures_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支