这是默认返回值:{“角色”:“ 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());但它确实有效,我的模型用户无法在受保护的空白中调用
您可以使用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
对象。希望有帮助。