【问题标题】:Java: User Authenticate Using Jersey Jax-RS with Spring SecurityJava:使用带有 Spring Security 的 Jersey Jax-RS 进行用户身份验证
【发布时间】:2014-08-30 07:41:22
【问题描述】:

我正在尝试使用 Jersey Jax-RS Api 和 Spring-Security 进行用户身份验证。但我能够做到这一点。 Jersey 提供了一些基本的身份验证方法,但我需要使用 spring-security。我正在尝试手动UserNamePassword 通过spring security 进行身份验证,但它抛出了空指针异常。以下是我的代码:

@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();
}
}

在此代码中,authenticationManager 为 null,因此它引发了异常。有没有另一种方法可以做到这一点?或者使用球衣Spring-Security 是不可能的?

请提供一些方法来做到这一点。

谢谢

【问题讨论】:

    标签: java rest spring-security jersey


    【解决方案1】:

    如果你想在你的项目中使用 Spring Security,你应该使用 AbstractAuthenticationProcessingFilter -> docs

    并覆盖 attemptAuthentication 方法。 在此方法的主体中,您将能够从 HttpRequest 获取您的用户名和密码。

    请记住使用 spring-security.xml 文件配置您的 spring 安全性。

    稍后在您的控制器 UserLoginApi 中,您将能够检查您的用户是否使用 SecurityContextHolder.getContext().getAuthentication() 成功验证。

    另见类:

    • org.springframework.security.web.authentication.AuthenticationFailureHandler

    • org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler

    • org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint

    【讨论】:

      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 2020-04-16
      • 2012-11-27
      • 2017-12-21
      • 2011-08-12
      相关资源
      最近更新 更多