通过身份验证提供者从Spring安全性到ReST API调用对用户进行身份验证

时间:2018-04-03 14:50:57

标签: spring-boot spring-security

我现在正在探索微服务中的用户身份验证。为此,我创建了我的身份验证服务 - checkUserAuthentication。还提供微服务。这已经部署在云端。    现在我正在使用特定的业务逻辑创建新服务。在此服务中,需要使用来自spring security的authenticationProvider来验证和检查用户的授权以访问此端点。

为此,我正在阅读并探索以下教程,

  1. https://dzone.com/articles/spring-security-custom
  2. http://roshanonjava.blogspot.in/2017/04/spring-security-custom-authentication.html
  3. http://javasampleapproach.com/spring-framework/spring-security/spring-security-customize-authentication-provider
  4. http://www.baeldung.com/spring-security-authentication-provider
  5. 在这里,他们在CustomAuthenticationProvider类中实现AuthenticationProvider。

    并且在方法中他们正在接收用户名和密码,如下所示,

    public Authentication authenticate(Authentication authentication) throws 
     AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
    
        Optional<User> optionalUser = users.stream().filter(u -> u.index(name, 
         password)).findFirst();
    
        if (!optionalUser.isPresent()) {
            logger.error("Authentication failed for user = " + name);
            throw new BadCredentialsException("Authentication failed for user = " + name);
        }
    
        // find out the exited users
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        grantedAuthorities.add(new SimpleGrantedAuthority(optionalUser.get().role));
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(name, password,
                grantedAuthorities);
    
        logger.info("Succesful Authentication with user = " + name);
        return auth;
    }
    

    这些是文档中的代码。而不是这种方法,我需要以不同的方式做。我在这里添加了我的要求:

    我的要求:我需要从API Request接收用户名和密码。要检查此用户名和密码,我需要调用已部署的API checkUserAuthentication和checkUserAuthorization。

    我对此表示怀疑:

    1. 我可以在“公共身份验证身份验证(身份验证身份验证)”方法中直接调用这些API吗?
    2. 我如何从收到的请求中收到用户名和密码?
    3. 为什么我们使用 UsernamePasswordAuthenticationToken ? ,如果我们发送JWT令牌而不是用户名和密码,那么哪个类将用于提供回复?
    4. 由于我只是从Spring Security开始,所以我是安全世界的新手。

1 个答案:

答案 0 :(得分:1)

  
      
  1. 我可以在“公共身份验证身份验证(身份验证身份验证)”方法中直接调用这些API吗?
  2.   

是。

  
      
  1. 我如何从收到的请求中收到用户名和密码?
  2.   

与认证方法相同。

  
      
  1. 为什么我们使用UsernamePasswordAuthenticationToken? ,如果我们发送JWT令牌而不是用户名和passowrd,那么哪个类   会用来提供回复吗?
  2.   

UsernamePasswordAuthenticationToken 由spring security在内部使用。这个 在春季创建会话时会出现在图片中。它包含用户信息(例如电子邮件等)和权限(角色)。例如,当您在应用程序中收到JWT令牌时,您将验证JWT令牌(签名等)并在成功验证JWT后,将创建UsernamePasswordAuthenticationToken的对象,spring将其保存在会话中。对于每个传入的请求,spring将在此对象上调用boolean isAuthenticated()方法以查找用户是否可以访问所需的资源。

现在,当你得到所有答案时,我的建议是使用Oauth2作为你的启动微服务。有很多示例如何实现它并根据您的要求进行自定义。 (基本上,您必须实现授权服务器,它将使用您的服务checkUserAuthentication对用户进行身份验证并生成accessstoken。您的微服务的每个使用者都需要发送他们从授权服务器和您获得的这个访问权限需要在你的微服务中验证它。所以你的微服务将充当资源服务器。)

希望它会有所帮助。