gpt4 book ai didi

spring - 在 AbstractAuthenticationProcessingFilter 中连接服务以添加身份验证详细信息

转载 作者:行者123 更新时间:2023-12-01 02:22:12 24 4
gpt4 key购买 nike

我想在安全认证过程中向 Authentication 对象添加自定义数据:

public class MyAuthFilter extends AbstractAuthenticationProcessingFilter {

MyUserDetailService userDetailService; // <==== How to wire??

@Override
public Authentication attemptAuthentication(
HttpServletRequest request,
HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
...
Authentication auth = new UsernamePasswordAuthenticationToken(
username,
r.sessionId,
Arrays.asList(new GrantedAuthority[]{new SimpleGrantedAuthority(grantedUserRole)}));
auth.setDetails(userDetailService.getDetail()); // <== Save detail to auth.
return auth;
}
}

如何连接 MyUserDetailService 服务?

如何将 MyUserDetailService 缓存到主体映射(以避免不必要的调用 userDetailService.getDetail() 并且不会因内存不足而崩溃)?

PS spring-security.xml :
<http use-expressions="true" auto-config="false" entry-point-ref="oauthEntryPoint" authentication-manager-ref="oauthAuthenticationManager">
<custom-filter position="FORM_LOGIN_FILTER" ref="myFilter" />
<intercept-url pattern="/login.htm" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<anonymous username="anonymous" enabled="true" granted-authority="AN" key="anonymous-security" />
<logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutHandler"/>
</http>

<beans:bean id="myFilter" class="com.web.filter.MyAuthFilter"> ...</beans:bean>

最佳答案

Spring Security 遵循通常的 Spring 架构,所以我的自定义 AbstractAuthenticationProcessingFilter只是普通的 bean 。

我不需要将类标记为 @Component正如它在 spring-security.xml 中声明的那样.我可以使用:

 @Autowired
private UserService userService;

或者:
public class MyAuthFilter
extends AbstractAuthenticationProcessingFilter
implements ApplicationContextAware {
private UserService userService;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
userService = applicationContext.getBean(UserService.class);
}
...
}

将 userDetailService.getDetail() 的值放入身份验证后:
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
userName, sessionId,
AuthorityUtils.createAuthorityList(grantedUserRole));
auth.setDetails(userService.get(userName));

它将自动缓存为与身份验证对象的 session 保持关联,并且在 session 失效后,此关联将传递给 GC。

关于spring - 在 AbstractAuthenticationProcessingFilter 中连接服务以添加身份验证详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19496987/

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