2014-09-30 33 views
0

我已阅读了与此主题相关的几个问题(Jersey REST API as a separate web app,Should web service be separate from web site?),但我仍然很难理解哪种设计实践对现有应用程序最有效。在现有的Web应用程序中创建一个API还是单独的?

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

同时,我将需要设计一个REST API,它将具有某种形式的认证/用户跟踪。 Web应用程序拥有自己的用户认证系统,可能与API实现(即username/pw vs api keys(?))不同。

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

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

回答

0

你可以使用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/

+0

我约上我的现有应用程序的顶部添加春季安全主要关注的是兼容现有的身份验证系统......或需要进行大规模更改才能使其工作。 – rcheuk 2014-09-30 17:38:33

+0

现有认证系统的体系结构是什么? – br1337 2014-09-30 17:42:17

+0

习俗,据我所知。一对夫妇控制器处理用户的会话,根据需要调用后端来登录用户并确定用户的权限(这会影响用户看到的屏幕) – rcheuk 2014-09-30 17:51:01

相关问题