Spring没有在控制器中注入主体

时间:2019-06-15 17:49:12

标签: java spring spring-boot spring-security

我有一个这样配置的自定义JWT授权过滤器:

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    private UserDetailsServiceImpl userDetailsService;

    public JWTAuthorizationFilter(AuthenticationManager authManager, UserDetailsServiceImpl userDetailsService) {
        super(authManager);
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain chain) throws IOException, ServletException {
        String header = req.getHeader(HEADER_STRING);

        if (header == null || !header.startsWith(TOKEN_PREFIX)) {
            chain.doFilter(req, res);
            return;
        }

        ExtendedUsernamePasswordAuthenticationToken authentication = getAuthentication(req);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(req, res);
    }

    private ExtendedUsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        if (token != null) {
            String user;
            try {
                // parse the token.
                user = JWT.require(Algorithm.HMAC512(SECRET.getBytes()))
                        .build()
                        .verify(token.replace(TOKEN_PREFIX, ""))
                        .getSubject();
            } catch (SignatureVerificationException e) {
                return null;
            }

            if (user != null) {
                UserPrincipal temp = (UserPrincipal) this.userDetailsService.loadUserByUsername(user);

                return new ExtendedUsernamePasswordAuthenticationToken(temp, null, temp.getAuthorities(), temp.getUser().getId());
            }
            return null;
        }
        return null;
    }
}

这将从正在发送的JWT令牌中读取用户,并将身份验证添加到安全上下文中。现在出现的问题是,每当我尝试将主体注入控制器中时,都会注入 ExtendedUsernamePasswordAuthenticationToken 。为什么会这样?

进样:

public ResponseEntity<?> getWalletsForUser(Principal principal) {

当我尝试将主体转换为自定义定义的主体时:

User user = ((UserPrincipal) principal).getUser();

我遇到的问题是强制转换失败,并且委托人是 ExtendedUsernamePasswordAuthenticationToken 的实例。

我在做什么错??

0 个答案:

没有答案
相关问题