使用UsernamePasswordAuthenticationFilter

时间:2015-11-14 01:45:40

标签: spring spring-security

我使用的是UsernamePasswordAuthenticationFilter的Spring和自定义实现。我想在成功验证后执行一些自定义代码(例如:使用刚认证的用户名记录消息)。

我应该覆盖哪种方法或如何注册处理程序以进行成功的身份验证?

最好是覆盖successfulAuthentication()方法,将自定义代码放在那里并通过调用原始方法(super.successfulAuthentication();)来完成它?还是有其他一些最好的做法?

2 个答案:

答案 0 :(得分:3)

  

成功后执行自定义任务的方法   身份验证是使用自定义身份验证成功处理程序   Spring Security。

您可以通过以下方式实现此目的:

创建自定义AuthenticationSuccessHandler,例如TMGAuthenticationSuccessHandler。我创建了一个示例代码,如果检测到用户使用默认的机器生成密码,则会将用户重定向到密码更改页面。

@Component("tMGAuthSuccessHandler")
public class TMGAuthSuccessHandler implements AuthenticationSuccessHandler {

    private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();

    @Autowired
    private UserService userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(TMGAuthSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication)
            throws IOException, ServletException {

        if (hasDefaultPassword(authentication)) {
            LOGGER.debug("Default password detected for username: " + authentication.getName());
            servletResponse.sendRedirect("changePassword");
        } else {
            target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
        }
    }

    /**
     * Checks whether default password is used in login.
     */
    private boolean hasDefaultPassword(Authentication authentication) {

        String username = authentication.getName();
        User user = userService.findOnUsername(username, true, false, false, false);
        if (user != null && user.getLoginAuditTrail() != null && user.getLoginAuditTrail().isDefaultPasswordUsed() != null) {
            return user.getLoginAuditTrail().isDefaultPasswordUsed();
        }
        return false;
    }

    /**
     * Proceeds to the requested URL.
     */
    public void proceed(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication) throws IOException,
            ServletException {
        target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
    }
}

修改包含弹簧安全相关配置的securityContext.xml或类似文件。将此customHander添加到http配置为authentication-success-handler-ref="tMGAuthSuccessHandler"。代码段如下所示:

<security:http use-expressions="true" authentication-manager-ref="webAppAuthManager">

    <!-- signin and signout -->
    <security:intercept-url pattern="/signin" access="permitAll" />
    <security:intercept-url pattern="/logout" access="permitAll" />
    <security:intercept-url pattern="/accessDenied" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />

    <!-- sign in Configuration -->
    <security:form-login login-page="/signin"
        username-parameter="username"
        password-parameter="password"
        authentication-failure-url="/signin?authFail=true"
        authentication-success-handler-ref="inoticeAuthSuccessHandler" />

    <security:logout logout-url="/signout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/signin?logout=true" />
</security:http>

你现在好了。

参考积分:How to use custom filter with authentication-success-handler-ref equivalent in spring security

答案 1 :(得分:1)