gpt4 book ai didi

Spring Security自动登录拦截

转载 作者:行者123 更新时间:2023-12-02 06:39:31 25 4
gpt4 key购买 nike

我已经使用 Spring Security 开发了一个注册和登录模块。我现在关心的是如何拦截自动存储的登录名以将信息保存在数据库中。我的意思是,当用户标记“记住我”时,如果进入我的应用程序,会自动转到登录主页,但我想在数据库中注册该访问权限。

现在,当用户显式访问登录页面时,很容易做到这一点,但在上述情况下则不然。

问候,

更新:我添加了一些额外信息:

  • security.xml

     <http auto-config="true">
    <form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/private/dashboard" />
    <remember-me key="rememberMeKey" user-service-ref="userServiceImpl" />
    </http>
    <authentication-manager alias="authenticationManager" />
    <authentication-manager>
    <authentication-provider user-service-ref="userServiceImpl">
    <password-encoder hash="md5"/>
    </authentication-provider>
    </authentication-manager>
  • userServiceImpl

    @Service
    @Transactional
    public class UserServiceImpl implements UserDetailsService {

    @Resource
    private UserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
    String password = userDao.getUserPassword(username);

    if (password!=null) {
    userDao.registerAccess(username);
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_REGISTERED"));
    return new User(username,password, AUTHORITIES);
    } else {
    throw new UsernameNotFoundException("User not found: " + username);
    }
    }

    }

最佳答案

这里有多种选择:

  • 设置 org.springframework.security.web.authentication。AuthenticationSuccessHandler
  • 订阅 org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent(请参阅@Ionut 答案)

AuthenticationSuccessHandler 将同样适用于您的两种情况(正常登录并记住我):

public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
// log authentication success here for both cases
super.onAuthenticationSuccess(request, response, authentication);
}

}

在您的security.xml中:

<bean id="customAuthenticationSuccessHandler" class="com.domain.security.CustomAuthenticationSuccessHandler"/>


<security:http ... >
...
<security:form-login login-page='/login.html' authentication-success-handler-ref="customAuthenticationSuccessHandler" />
<security:remember-me authentication-success-handler-ref="customAuthenticationSuccessHandler" />

</security:http>

关于Spring Security自动登录拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14354034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com