SpringSecurity自定义UsernamePasswordAuthenticationFilter
UsernamePasswordAuthenticationFilter介紹
UsernamePasswordAuthenticationFilter是AbstractAuthenticationProcessingFilter針對(duì)使用用戶(hù)名和密碼進(jìn)行身份驗(yàn)證而定制化的一個(gè)過(guò)濾器。其添加是在調(diào)用http.formLogin()時(shí)作用,默認(rèn)的登錄請(qǐng)求pattern為"/login",并且為POST請(qǐng)求。當(dāng)我們登錄的時(shí)候,也就是匹配到loginProcessingUrl,這個(gè)過(guò)濾器就會(huì)委托認(rèn)證管理器authenticationManager來(lái)驗(yàn)證登錄。
自定義UsernamePasswordAuthenticationFilter
這里我的需求是通過(guò)自定義UsernamePasswordAuthenticationFilter實(shí)現(xiàn)對(duì)前端傳過(guò)來(lái)的密碼進(jìn)行RSA私鑰解密,并且因?yàn)榈卿浀刂凡皇?#34;/login",所以繼承的是AbstractAuthenticationProcessingFilter,如果登錄地址為默認(rèn),那么可直接繼承UsernamePasswordAuthenticationFilter重寫(xiě)attemptAuthentication方法即可。
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;private boolean postOnly = true;private String privateKey = "xxxxxxxxxxxxxxxxxxx";public MyUsernamePasswordAuthenticationFilter() {super(new AntPathRequestMatcher("/oauth/token", "POST"));}public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)throws AuthenticationException {if (postOnly && !request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());}String username = obtainUsername(request);String password = obtainPassword(request);try {password = RSAUtil.decrypt(password, privateKey);} catch (Exception e) {e.printStackTrace();}if (username == null) {username = "";}if (password == null) {password = "";}username = username.trim();UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);// Allow subclasses to set the "details" property setDetails(request, authRequest);return super.getAuthenticationManager().authenticate(authRequest);}public void setAuthenticationManager(AuthenticationManager authenticationManager) {super.setAuthenticationManager(authenticationManager);}protected String obtainPassword(HttpServletRequest request) {return request.getParameter(passwordParameter).replaceAll(" ", "+");}protected String obtainUsername(HttpServletRequest request) {return request.getParameter(usernameParameter);}protected void setDetails(HttpServletRequest request,UsernamePasswordAuthenticationToken authRequest) {authRequest.setDetails(authenticationDetailsSource.buildDetails(request));}public void setUsernameParameter(String usernameParameter) {Assert.hasText(usernameParameter, "Username parameter must not be empty or null");this.usernameParameter = usernameParameter;}public void setPasswordParameter(String passwordParameter) {Assert.hasText(passwordParameter, "Password parameter must not be empty or null");this.passwordParameter = passwordParameter;}public void setPostOnly(boolean postOnly) {this.postOnly = postOnly;}public final String getUsernameParameter() {return usernameParameter;}public final String getPasswordParameter() {return passwordParameter;}}把自定義 MyUsernamePasswordAuthenticationFilter 添加到 Filter Chain 過(guò)濾器鏈中
在 SpringSecurity 的配置類(lèi)中使用 http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) 把自定義的過(guò)濾器放在UsernamePasswordAuthenticationFilter 的位置,并為其設(shè)置認(rèn)證成功和失敗的處理方法以及認(rèn)證管理器AuthenticationManager
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate AuthenticationSuccessHandler appLoginInSuccessHandler;@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {AuthenticationManager manager = super.authenticationManagerBean();return manager;}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().cors().disable().headers().frameOptions().sameOrigin();// 解決iframe無(wú)法訪(fǎng)問(wèn)http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);}@Bean MyUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();filter.setAuthenticationManager(authenticationManagerBean());filter.setAuthenticationSuccessHandler(appLoginInSuccessHandler);filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");response.getWriter().write(JSON.toJSONString(Respon.failed("登錄失敗!")));}});return filter;} }自定義UsernamePasswordAuthenticationFilter的運(yùn)用
除了上面的例子,還常用于修改表單登錄變?yōu)槭褂肑son格式登錄,登錄驗(yàn)證碼等等,需要注意的地方是UsernamePasswordAuthenticationFilter的默認(rèn)登錄地址為
?
轉(zhuǎn)載于:https://www.cnblogs.com/dang-/p/11535940.html
總結(jié)
以上是生活随笔為你收集整理的SpringSecurity自定义UsernamePasswordAuthenticationFilter的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 瑞幸咖啡自曝虚假交易 22 亿,App
- 下一篇: 什么鬼?弃用JDK动态代理,Spring