1

I want to generate JWT if the username password provided are accurate. I have a userdetailservice and I am using AbstractUserDetailsAuthenticationProvider. Here is my code:

public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter { public JwtAuthenticationTokenFilter() { super("/rest/**"); } @Override public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException { String header = httpServletRequest.getHeader("Authorisation"); if (header == null || !header.startsWith("Token")) { throw new RuntimeException("JWT Token is missing"); } String authenticationToken = header.substring(6); JwtAuthenticationToken token = new JwtAuthenticationToken(authenticationToken); return getAuthenticationManager().authenticate(token); } 

When I try to login it returns a JWT even if the password is wrong.

@RestController @RequestMapping("/token") public class TokenController { private JwtGenerator jwtGenerator; public TokenController(JwtGenerator jwtGenerator) { this.jwtGenerator = jwtGenerator; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String createAuthenticationToken( @RequestBody User user, HttpServletResponse response) throws AuthenticationException, IOException { return jwtGenerator.generate(user); } 

My understanding is when a user tries to login, validation of the user's identity is made by the user detail service which is loaded by username, so I dont know why its not working.

This is part of my security config:

@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().antMatchers("**/rest/**").authenticated() .and() .exceptionHandling().authenticationEntryPoint(entryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); http.headers().cacheControl(); } 

1 Answer 1

1

Your problem is that when you call the request login you are not authenticating user, you are just creating token, you are not checking if your password is valid or not so first in your login service you have to add this code:

@RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseEntity<?> login(@RequestBody LoginUser loginUser) throws AuthenticationException { final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginUser.getUsername(), loginUser.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authentication); final String token = jwtTokenUtil.generateToken(authentication); User user = userService.getUserByUsername(loginUser.getUsername()); user.setToken(token); return ResponseEntity.ok(user); } 

LoginUser is java class with just two fields username and password with constructor, getters and setters of this two fields.

final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginUser.getUsername(), loginUser.getPassword() ) ); 

this code will check username and password validity, it will go itself to loadbyusername function which is defined in userdetails class and if username or password was wrong api will return bad credentials error but for that you need extra code to write.

create class:

@Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } } 

and after that initialize object of the JwtAuthenticationEntryPoint class in your security config class like this:

@Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; 

and add this code in your configure function in web security configuration class:

.exceptionHandling().authenticationEntryPoint(unauthorizedHandler) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.