0
我做了一個自定義過濾器和failureHandler。但爲了使其工作,我需要在過濾器中註冊處理程序。所以我會很高興,如果有人會寫我的代碼如何做。我知道stackowerflow中有很多例子,但是我對spring和java很陌生,爲了理解它如何工作,我需要爲我的應用程序提供一個示例。請不要回答「這是重複的」。 我的過濾器:如何在自定義過濾器彈簧安全中註冊自定義FailureHandler
@Component("MyAuthFilter")
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter {
private int errCode = 5;
@Autowired
@Qualifier("authenticationManager")
@Override
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
System.out.println("running my own version of UsernmePasswordFilter ... ");
String login = (String) request.getParameter("login");
String password = (String) request.getParameter("password");
errCode = validate(login, password);
System.out.println(login + " - " + password);
System.out.println(request.getQueryString());
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(login, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
private int validate(String login, String password) {
if (login.isEmpty() && password.isEmpty()) {
return 4;
}
if (login.isEmpty() && !password.isEmpty()) {
return 2;
}
if (!login.isEmpty() && password.isEmpty()) {
return 3;
}
return 1;
}
}
這裏是我的處理程序:
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
public LoginFailureHandler() {
System.out.println("i debug");
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
System.out.println("do smth");
super.onAuthenticationFailure(request, response, exception);
}
}
和我的彈簧security.xml文件:
<beans:bean id="authenticationFailureHandler" class="com.webproject.LoginFailureHandler" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/courses*" access="hasRole('ROLE_USER')" />
<custom-filter before="FORM_LOGIN_FILTER" ref="MyAuthFilter" />
<form-login
login-page="/login"
default-target-url="/courses"
username-parameter="loginField"
password-parameter="passwordField"
authentication-failure-handler-ref="authenticationFailureHandler"
/>
<csrf disabled="true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="ars" password="1234" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
,或者你可以只用標記@Component – kuhajeyan
我使用XML文件處理程序,我已經宣佈它是這樣的: '<豆類:豆類ID =「authenticationFailureHandler」級=」 com.webproject.LoginFailureHandler「/> – Papich
那應該足夠了 – kuhajeyan