将用户添加到会话中,Spring Security默认登录
我已经设置了spring安全性以正确拦截并使用自定义登录页面提示用户,然后正确进行身份验证并将用户详细信息添加到SecurityContextHolder。
作为补充,我现在想在每次登录时将自己的自定义User对象添加到会话中;因此代码如下所示:
public returnwhat? doMySupplementaryLogin() { UserDetails principal = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
MyUser user = myUserService.getMyUser(principal.getUsername());
add user to what ?
}
这段代码会去哪儿?我希望执行名义弹簧认证,然后上面的代码会将MyUser对象放入会话中,然后将用户发送到原始截获的url /
viewname。我有一种强烈的感觉,我正在使事情变得比他们需要的复杂。
回答:
您确实使其变得复杂… :)
您想要的是向Spring的常规身份验证管理器中添加自定义身份验证提供程序。因此,您可以这样配置身份验证管理器:
<security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="authServiceImpl">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
现在,您只需要在spring上下文中定义authServiceImpl bean。您可以通过xml或注释(我的首选方式)来完成此操作。
@Servicepublic class AuthServiceImpl implements AuthService {
您需要实现AuthService接口。只需从接口实现方法即可-应该非常简单。您不需要自己将东西放到SecurityContextHolder中-
spring可以做到这一点。
您想要的是:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { return MyUser user = myUserService.getMyUser(username);
}
随时询问您是否还有其他问题。
编辑:或者您可以只让您的UserService类实现该接口-我这样做是因为您没有提供UserService类。
以上是 将用户添加到会话中,Spring Security默认登录 的全部内容, 来源链接: utcz.com/qa/421473.html