I am trying to use Jersey Jax-RS Api and Spring-Security for user authenticate. But i am enable to do this. Jersey provide some basic authentication methods, but i need to use spring-security. I am trying manually UserName
and Password
authenticate by spring security, but it thrown and null pointer exception. Follwoing is my code :
@Path(value = "/")
public class UserLoginApi {
@Autowired
private AuthenticationManager authenticationManager;
@POST
@Path(value = "test")
public void test() {
System.out
.println("Hello REST **************************************** ");
}
@POST
@Path(value = "login")
@Consumes(MediaType.APPLICATION_JSON)
public Response userlogin(User user, @Context HttpServletRequest request) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword());
Authentication authentication = authenticationManager.authenticate(authenticationToken);
User user2 = (User) SecurityContextHolder.getContext();
System.out.println(user2);
return Response.status(200).entity("OK").build();
}
}
In this code the authenticationManager
is null, so it thrown an exception. Is there is a another way for do this? or using jersey the Spring-Security
is not possible?
Please provide some way for do this.
Thanks
If you want to use spring security in your project you should use AbstractAuthenticationProcessingFilter -> docs
and override attemptAuthentication method. In the body of this method you will be able to get your username and password from HttpRequest.
Please remember to configure your spring security using spring-security.xml file.
Later in your controller UserLoginApi you will be able to check if your user authenticated successfully using SecurityContextHolder.getContext().getAuthentication() .
See also classes:
org.springframework.security.web.authentication.AuthenticationFailureHandler
org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint
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.