I want to return my id so i can use it, the question is how can i do that**
this is the default return : { "role": "ROLE_XXXX", "succeed": "Berhasil Login", "username": "xxxx@gmail.com", "token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }
this is what i want : { "id": 123, "role": "ROLE_XXXX", "succeed": "Berhasil Login", "username": "xxxx@gmail.com", "token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }
and there's my code :
@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();
}
i'am try to call my model "User" so i can call like this map.put("id", user.getId()); but it dosent work my model user cant call in protected void
You can use Authentication
object to getName of the principal.
For example: auth.getName()
will give the name of the Principle. Use this name in order to retrieve User
from the database and put the id accordingly.
In your filter, you can constructor inject the ApplicationContext
and get bean of your repository/dao
according to your need. I am using a repository for an example:
public JwtAuthenticationFilter(AuthenticationManager authenticationManager, ApplicationContext context) {
this.repository = context.getBean(UserRepository.class);
}
And inorder to create the object of JwtAuthenticationFilter
, you need ApplicationContext
object and you can easily get it by autowiring.
@Autowired
private ApplicationContext context;
Then
new JwtAuthenticationFilter(authenticationManager, context);
Now you can use the repository to get the User
object. Hope, it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.