在Spring Security中,如何配置自定義登錄? spring security添加自定義用戶信息
Mintifi優(yōu)選達(dá)人跨境問(wèn)答2025-05-137350
在Spring Security中,你可以使用@PreAuthenticated注解來(lái)配置自定義登錄。以下是一個(gè)示例:
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter.ChainMatcher;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter.CredentialsProvider;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter.Customizer;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter.SuccessHandler;
public class CustomAuthenticationFilter extends BasicAuthenticationFilter {
private String username;
private String password;
public CustomAuthenticationFilter(String username, String password) {
super("/api/login");
this.username = username;
this.password = password;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String username = getUsernameFromRequest(request);
String password = getPasswordFromRequest(request);
if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) {
Authentication authentication = new PreAuthenticatedAuthenticationToken(username, password);
addSuccessHandler(new SuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
response.setStatus(HttpStatus.SC_OK);
chain.doFilter(request, response);
}
});
} else {
chain.doFilter(request, response);
}
}
private String getUsernameFromRequest(HttpServletRequest request) {
return request.getParameter("username");
}
private String getPasswordFromRequest(HttpServletRequest request) {
return request.getParameter("password");
}
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)繼承自BasicAuthenticationFilter的自定義過(guò)濾器,并重寫(xiě)了doFilterInternal方法。在這個(gè)方法中,我們從請(qǐng)求參數(shù)中獲取用戶名和密碼,然后使用這些信息創(chuàng)建一個(gè)新的PreAuthenticatedAuthenticationToken對(duì)象,并將其添加到過(guò)濾器鏈中。
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。