Spring Security:如果身份验证失败,则重定向到登录页面 [英] Spring Security : Redirecting to login page if the authentication failed
问题描述
我们有两种登录方式.
当请求标题中包含用户名和密码时,如果输入错误,我将显示 HTTP状态401-身份验证失败:凭据错误页面.
When the user name and password are present in the request header and if it's wrong, I am shown an HTTP Status 401 - Authentication Failed: Bad credentials page.
如果身份验证失败,如何显示登录页面?
How do I make it show the login page in case the authentication failed?
下面是security.xml中的代码
Below is the code in the security.xml
<http auto-config="true" use-expressions="true">
<access-denied-handler error-page="/login.jsp"/>
<intercept-url pattern="/*Login*" access="hasRole('ROLE_ANONYMOUS')"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')"/>
<custom-filter ref="requestHeaderFilter" before="FORM_LOGIN_FILTER"/>
<form-login login-page="/login.jsp"/>
</http>
如果您需要更多信息,请告诉我.
Please let me know if you need more information.
在我的应用程序中为RequestHeader过滤器添加代码
Adding the code for RequestHeader filter in my application
public class RequestHeaderProcessingFilter extends AbstractAuthenticationProcessingFilter{
private String usernameHeader = "j_username";
private String passwordHeader = "j_password";
protected RequestHeaderProcessingFilter() {
super("/login_direct");
}
//getters and setters
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String username = request.getHeader(usernameHeader);
String password = request.getHeader(passwordHeader);
SignedUsernamePasswordAuthenticationToken authRequest =
new SignedUsernamePasswordAuthenticationToken(username, password);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
推荐答案
要在身份验证失败的情况下显示登录页面,您应该在<access-denied-handler error-page="/login.jsp"/>
和<intercept-url pattern="/*Login*" access="hasRole('ROLE_ANONYMOUS')"/>
To show the login page in case the authentication failed you should have the same url in the <access-denied-handler error-page="/login.jsp"/>
and the <intercept-url pattern="/*Login*" access="hasRole('ROLE_ANONYMOUS')"/>
例如:
<global-method-security secured-annotations="enabled" />
<http auto-config="true" access-denied-page="/app/sesiones/procesarLogin">
<logout logout-success-url="/app/sesiones/login" />
<form-login
authentication-failure-url="/app/sesiones/login?error=true"
login-page="/app/sesiones/login" default-target-url="/app/sesiones/procesarLogin" />
<intercept-url pattern="/app/privados/*" access="ROLE_USER" />
</http>
在该示例中,用户注销后也将重定向到登录页面. /procesarLogin是一种将用户发送到login.jsp页面的方法.
in that example, the user is also redirected to login page after he logs out. The /procesarLogin is a method that sent user lo login.jsp page.
这篇关于Spring Security:如果身份验证失败,则重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!