如何使用angular 2 Spring MVC Application

时间:2017-02-04 07:37:54

标签: spring spring-mvc angular spring-security

基本上,我想在angular2 Web应用程序中使用spring security实现身份验证和授权。对于Angular 2应用程序,我使用angular-cli版本" 1.0.0-beta.21"用于部署和构建。这两个项目都不是单个应用程序的一部分.Angular 2 App部署在部署在Tomcat Server上的Apache和Spring MVC应用程序上。我正在使用Spring 4.。

当我尝试使用我的Spring应用程序页面登录时#34; login.jsp"响应以所需的格式出现,因为会话一次性正确捕获上下文,而当我使用我的角度应用程序会话时,无法加载上下文,从而无法提供身份验证标志值。

以下是My SecurityConfiguration.Java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    PersistentTokenRepository tokenRepository;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/", "/list")
                .access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
                .antMatchers("/newuser/**", "/delete-user-*").access("hasRole('ADMIN')").
                antMatchers("/edit-user-*") .access("hasRole('ADMIN') or hasRole('DBA')").and().formLogin().loginPage("/login")
                .loginProcessingUrl("/login").usernameParameter("ssoId").passwordParameter("password").and()
                .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
                .tokenValiditySeconds(86400).and().csrf().disable().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {

        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {

        PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
                "remember-me", userDetailsService, tokenRepository);
        return tokenBasedservice;
    }

    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {

        return new AuthenticationTrustResolverImpl();
    }

}

Controller Class ::

@CrossOrigin
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {     
        if (isCurrentAuthenticationAnonymous()) {           
            return "login";
        } else {            
            return "redirect:/list";  
        }
    }

private boolean isCurrentAuthenticationAnonymous() {
    Logger.getLogger("AppName").debug("In isCurrentAuthenticationAnonymous method ");
       final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       Logger.getLogger("AppName").debug("authentication value is " +authentication.toString());
       boolean flag = authenticationTrustResolver.isAnonymous(authentication);
       Logger.getLogger("AppName").debug("Flag value for anonymous user is " +flag);
       return flag;
    }

重要 所以,当我们点击这个' / login'使用带有经过身份验证的凭据的spring应用程序,flag会按预期变为false,因为上下文加载器可以完美地完成其工作。

由于我的前端角度应用程序在不同的实例上运行,我已设法编写一段代码,时间如下:

@CrossOrigin
    @RequestMapping(value = "/userDetaiils/{ssoId}", method = RequestMethod.GET)
    public @ResponseBody UserDetails userDetails(@PathVariable String ssoId,@PathVariable String Password) {
    if (isCurrentAuthenticationAnonymous()) {
    Logger.getLogger("AppName").debug("called isCurrentAuthenticationAnonymous method ");

       }
    return customUserDetailsService.loadUserByUsername(ssoId);
    }

此代码始终将标志返回为true,因为未加载上下文。 以下是我现在主要坚持的观点。

作为angular2中的新手用户,下面是附加API的附加代码

authenticateLogin(uname,pwd): Observable<Object[]>{
    return this.http.get('http://localhost:8090/AppName/userDetails?ssoId='+uname+'&&password='+pwd)
            // ...and calling .json() on the response to return data
            .map((res:Response) => res.json())
            //...errors if any
            .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }

欢迎任何类型的建议,如果我出错了,请纠正。

0 个答案:

没有答案