網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
自定義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請(qǐng)求
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();
}
/**
* 自定義認(rèn)證過(guò)濾器
* @return
* @throws Exception
*/
@Bean
public MyUsernamePasswordAuthenticationFilter get() throws Exception {
MyUsernamePasswordAuthenticationFilter myLoginFilter = new MyUsernamePasswordAuthenticationFilter();
myLoginFilter.setUsernameParameter("u");
myLoginFilter.setPasswordParameter("p");
myLoginFilter.setFilterProcessesUrl("/xplogin"); // 指定認(rèn)證的請(qǐng)求
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("認(rèn)證失敗");
}
});
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("認(rèn)證失敗");
}
});
return myLoginFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin();
http.authorizeRequests()
.anyRequest().authenticated();
http.csrf().disable();
// at是用filter去替換某個(gè)filter
http.addFilterAt(get(), UsernamePasswordAuthenticationFilter.class);
}
}
測(cè)試接口
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 "小老弟你來(lái)啦";
}
}
隨手一個(gè)依賴吧
<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
相關(guān)推薦
- 2023-09-12 利用Map結(jié)合Supplier消除switch...case
- 2022-12-07 C++11?lambda表達(dá)式在回調(diào)函數(shù)中的使用方式_C 語(yǔ)言
- 2022-07-06 C#數(shù)據(jù)適配器DataAdapter_C#教程
- 2022-07-15 Python打印數(shù)據(jù)類型的全過(guò)程_python
- 2022-11-14 python中的運(yùn)算符
- 2022-10-12 python?time時(shí)間庫(kù)詳解_python
- 2022-03-21 C++名稱空間介紹_C 語(yǔ)言
- 2023-05-08 C語(yǔ)言中棧的結(jié)構(gòu)和函數(shù)接口的使用示例_C 語(yǔ)言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支