【发布时间】:2018-10-19 05:05:51
【问题描述】:
我有一个问题来自阅读 Spring 用户和 oauth2 的大量示例,但在一些基本概念上仍然失败,也许有人可以为我指出好的方向/示例或要阅读的信息。
所以我正在尝试构建一个基于休息的 API 应用程序。 要访问端点,它们将受到 JWT 令牌的保护,其想法是令牌用于跨多个其他应用程序的 SSO。
我最初的想法是使用一些身份验证过滤器拦截器来处理令牌,这样我就可以存储我可能需要的任何其他信息,然后在我的服务的实际业务层中使用该用户。 我已经实现了一些实现过滤器的 AuthenticationFiler 从我的令牌存储中读取令牌访问权限后,我可以获得其他信息。
现在我的第一个问题实际上是大多数示例都是从登录/注销页面开始的,因为我有更多的 API 设置,所以我真的没有那种流程。
其次,似乎大多数时候获取用户的方式是从主体 (SecurityContextHolder.getContext().getAuthentication().getPrinciple()) 类似这样的东西,但我的主体始终为空,不确定这是不是因为我真的不知道这是因为有状态还是无状态。
所以我最大的问题是了解如何在我的安全拦截器和我的业务层之间共享用户详细信息。也许这个问题与spring本身无关,我缺少更多的基础知识,但也许有人可以给我一些指点。
这是我的身份验证过滤器,我想知道如何创建用户实例,就像使用 MDC 存储用户信息一样。 理想情况下,我想在那里创建一个用户实例并将其传递给业务层。我可以用 Autowire 做到这一点吗?
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class AuthenticationFilter implements Filter {
@Autowired
TokenStore tokenStore;
@Autowired
JwtAccessTokenConverter accessTokenConverter;
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
if (authentication instanceof OAuth2Authentication) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
OAuth2AuthenticationDetails oauth2AuthenticationDetails = (OAuth2AuthenticationDetails)oAuth2Authentication.getDetails();
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(oauth2AuthenticationDetails.getTokenValue());
Object decodedDetails = oauth2AuthenticationDetails.getDecodedDetails();
Map<String, Object> additionalInformation = oAuth2AccessToken.getAdditionalInformation();
MDC.put("sub", additionalInformation.get("sub").toString());
MDC.put("preferred_username", additionalInformation.get("preferred_username").toString());
}
}
try {
chain.doFilter(request, response);
}
finally {
MDC.remove("sub");
MDC.remove("preferred_username");
}
}
@Override
public void destroy() {
}
}
不确定这是否是我的误解,但我认为我正在寻找的是依赖注入。
不知何故,我想创建一个新的用户 Bean,将其填充到我的过滤器中并在其他地方使用它。 我想我可以在我的业务层中做一个@autowire 并将其设置在过滤器中并在业务层中使用它? 这是一个糟糕的模式吗?
【问题讨论】:
-
在此处分享您的身份验证过滤器代码。
-
刚刚这样做,我不确定这是否有帮助
标签: spring-security spring-security-oauth2 spring-oauth2