显示Spring Boot API JWT中的ID

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

enter image description here 我想返回我的ID,以便我可以使用它,问题是我该怎么做

这是默认返回值:{“角色”:“ ROLE_XXXX”,“成功”:“ Berhasil登录”,“用户名”:“ [email protected]”,“令牌”:“ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”}

这就是我想要的:{“ id”:123,“角色”:“ ROLE_XXXX”,“成功”:“ Berhasil登录”,“用户名”:“ [email protected]”,“令牌”:“ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”}

还有我的代码:

@Override
protected void successfulAuthentication(final HttpServletRequest req, final HttpServletResponse res, final FilterChain chain,
        final Authentication auth) throws IOException, ServletException {
    logger.info("successfulAuthentication");
    logger.info(auth);
    Set<String> roles = AuthorityUtils.authorityListToSet(auth.getAuthorities());
            String hasil=roles.toString().replace("[","").replace("]", "");

    Map map = new HashMap(); 
    map.put("username", auth.getName());
    map.put("role", hasil);
    map.put("token", AuthenticationService.addToken(auth.getName()));
    map.put("succeed", "Berhasil Login");

    String authString = new Gson().toJson(map);


    PrintWriter out = res.getWriter();
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");
    out.print(authString);
    out.flush(); 

}

我尝试将我的模型称为“用户”,这样我就可以这样称呼map.put(“ id”,user.getId());但它确实有效,我的模型用户无法在受保护的空白中调用

java spring api jwt boot
1个回答
0
投票

您可以使用Authentication对象获取主体的名称。

例如:auth.getName()将给出原理的名称。使用此名称以便从数据库中检索User并相应地放置ID。

在过滤器中,您可以根据需要构造函数注入ApplicationContext并获取repository/dao的bean。我以存储库为例:

public JwtAuthenticationFilter(AuthenticationManager authenticationManager, ApplicationContext context) {
    this.repository = context.getBean(UserRepository.class);
}

并且为了创建JwtAuthenticationFilter的对象,您需要ApplicationContext对象,并且可以通过自动装配轻松获得它。

@Autowired 
private ApplicationContext context;

然后

new JwtAuthenticationFilter(authenticationManager, context);

现在您可以使用存储库获取User对象。希望有帮助。

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