如何在Spring Security中扩展已登录的用户信息?

问题描述 投票:0回答:1

我正在使用this tutorial作为我的应用程序的基础。现在,我想用其他信息(用户ID和电子邮件地址)扩展当前登录的用户。目标是使蜜蜂能够在控制器中执行此操作:authentication.getId()authentication.getPrincipal().getId()

在给定的教程中,我不太了解一些要素:

  1. UserDetailsS​​erviceImpl的作用是什么?
  2. UsernamePasswordAuthenticationToken怎么了?

在一个地方这样使用:

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

            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }

同时以其他方式:

return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>())

我必须扩展User类,还是以某种方式扩展UsernamePasswordAuthenticationToken?期待您的回答!

spring spring-boot spring-security
1个回答
0
投票

将所需的主体设置为Authentication

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain chain) throws IOException, ServletException {
        ...
        String username = getUsername(req);
        ApplicationUser applicationUser = applicationUserRepository.findByUsername(username);
        Authentication authentication = new UsernamePasswordAuthenticationToken(applicationUser, null, new ArrayList<>());

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

(在上面的示例中,将登录的ApplicationUser设置为主体。]

然后,控制器可以通过SecurityContext获取委托人:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ApplicationUser principal = (ApplicationUser) authentication.getPrincipal();
    System.out.println(principal.getId());

Here is complete diff


UserDetailsS​​erviceImpl的作用是什么?

Here is UserDetailsService description

UserDetailsService是DAO界面,用于加载特定于用户帐户的数据。除了加载该数据以供框架中的其他组件使用外,它没有其他功能。它不负责验证用户身份。使用用户名/密码组合对用户进行身份验证通常是由UserDetailsService执行的,DaoAuthenticationProvider被注入UserDetailsService以便允许它为用户加载密码(和其他数据),以便将其与提交的密码进行比较值。

UsernamePasswordAuthenticationToken发生了什么?

普通,用作DaoAuthenticationProvider#authenticate's argument(另请参见DaoAuthenticationProvider#authenticate)。在本教程中,它由supports调用。

[另一方面,supports也使用JWTAuthenticationFilter,但是这里不需要这种类型(仅用作JWTAuthenticationFilter实现。]]

© www.soinside.com 2019 - 2024. All rights reserved.