i have some problem while i wanna using my service on Authentication Filter in java. here my code
AuthenticationFilter.java
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Autowired
private AuthenticationManager authManager;
@Autowired
private UserService userService;
public AuthenticationFilter(AuthenticationManager authManager) {
this.authManager = authManager;
super.setFilterProcessesUrl("/api/login");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
User user = new User();
try {
Object req = request.getInputStream();
user = new ObjectMapper().readValue(request.getInputStream(), User.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return authManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUname(), user.getPass()));
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
String secretKey = "$2y$18$1d12QDK72RFixzHcDqKYjODHA36NAsKm1RIu5V1DsgbPJAxvH0R22";
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes());
long expiredDate = 900000000;
String tokenStr = Jwts.builder().signWith(key).setSubject(authResult.getName())
.setExpiration(new Date(new Date().getTime() + expiredDate)).compact();
UserHelper usr = new UserHelper();
User u = new User();
System.out.println(authResult.getName());
String uname = authResult.getName();
System.out.println(uname);
try {
u = userService.findByUname(uname, uname);
usr.setUser(u);
usr.setToken(tokenStr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/json");
response.getWriter().append("{\"token\":\"" + tokenStr + "\"}");
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
and the error message is
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.lawencon.security.AuthenticationFilter required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
i try to use @Autowired, and @ Bean before constructor but the Annotations have dissallowed location. for this case i wanna send response jwt and roles name
if i use bean annotations on this code
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationFilter(AuthenticationManager authManager) {
this.authManager = authManager;
super.setFilterProcessesUrl("/api/login");
}
the annotations is disallowed location