【问题标题】:Create an API within existing web application or separate?在现有 Web 应用程序中创建 API 还是单独创建?
【发布时间】:2014-09-30 17:13:03
【问题描述】:

我已经阅读了一些与此主题相关的问题(Jersey REST API as a separate web appShould web service be separate from web site?),但我仍然难以理解哪种设计实践最适合现有应用程序。

我继承了一个基于 spring 和 hibernate JPA 构建的 java web 应用程序。它目前正在生产中,正在开发新功能。

同时,我需要设计一个具有某种形式的身份验证/用户跟踪的 REST API。 Web 应用程序有自己的用户身份验证系统,该系统可能与 API 实现不同(即用户名/密码与 api 密钥 (?))。

鉴于这种情况,我认为最好单独开发它们,但我觉得一开始会有很多代码重复(由于所有 jpa 在 Web 应用程序中实现)。理想情况下,一旦我有了其余的 api,我会切换 web 应用程序以使用该 API,并删除当前处理数据检索的大部分后端代码。

在我开始这条路线之前,我想知道,有没有更好的方法来做到这一点?

【问题讨论】:

    标签: java spring api rest jpa


    【解决方案1】:

    您可以使用 Spring Security 并创建自定义 AuthenticationProvider 。您可以使用 JNDI 查找直接从它自己的 Container 获取 authservice。

    例子:

    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {
         @Autowired
         private AuthService authService; 
    
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
    
        // use the credentials to try to authenticate against the third party system
        if (authService(name, password)) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
        } else {
            throw new AuthenticationException("Unable to auth against third party systems");
        }
    }
    
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    

    此外,在此处阅读有关使用 Spring 的 RESTful api 的更多信息:

    http://www.baeldung.com/rest-with-spring-series/

    【讨论】:

    • 我对在现有应用程序之上添加 Spring Security 的主要担忧是与现有身份验证系统的兼容性......或者需要进行大量更改才能使其正常工作。
    • 现有认证系统的架构是怎样的?
    • 自定义,据我所知。几个控制器处理用户的会话,根据需要调用后端以登录用户并确定用户的权限(这会影响用户看到的屏幕)
    • 我不确定我是否了解问题的所有背景。您有一个在其自己的身份验证服务上运行的遗留应用程序,您需要构建一个不同的服务作为 RESTful API,并且您需要对两者进行身份验证,对吗?如果这是问题所在,您可以通过现有的 Web 应用程序服务找到一种对 RESTful Web 服务进行身份验证的方法。如果您需要对两者进行身份验证,您可以编写一个执行身份验证的 API,并在 Web api 和 RESTful 服务中实现它。
    • 我不会将其称为遗留应用程序,因为它仍然需要在构建 api 时/之后运行/运行。我需要创建一个安全的 REST API(考虑使用 api 密钥或类似的东西;仍在研究这方面)。该应用程序当前确实使用 REST(大部分但不完全)来处理数据请求,但它并没有完全锁定。应用程序的大多数身份验证都是通过用户登录进行的。我怀疑在 Web 应用程序中维护和保护现有的 REST 服务会很困难,因此提出了这个问题。
    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    相关资源
    最近更新 更多