2017-08-16 127 views
0

我有一个角度2前端和弹簧引导后端的应用程序。我正在使用弹簧启动安全性csrf,通过遵循教程启用,并希望保持这种方式。对接我现在面临的rpoblem,当我从angular 2应用程序发布用户注册请求时,我得到了403禁止的错误。但是使用登录POST方法工作。弹簧引导角度2后置方法403错误

这里是我的春天启动安全配置:

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

String [] publicUrls = new String [] { 
     "/api/public/**", 
     "/api/login", 
     "/api/logout", 
     "/api/register", 
     "/api/register/**" 
}; 

@Value("${jwt.cookie}") 
private String TOKEN_COOKIE; 

@Bean 
public TokenAuthenticationFilter jwtAuthenticationTokenFilter() throws Exception { 
    return new TokenAuthenticationFilter(); 
} 

@Bean 
@Override 
public AuthenticationManager authenticationManagerBean() throws Exception { 
    return super.authenticationManagerBean(); 
} 

@Bean 
public PasswordEncoder passwordEncoder() { 
    return new BCryptPasswordEncoder(); 
} 

@Autowired 
private CustomUserDetailsService jwtUserDetailsService; 

@Autowired 
private RestAuthenticationEntryPoint restAuthenticationEntryPoint; 

@Autowired 
private LogoutSuccess logoutSuccess; 

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { 
    authenticationManagerBuilder 
      .userDetailsService(jwtUserDetailsService) 
      .passwordEncoder(passwordEncoder()); 

} 

@Autowired 
private AuthenticationSuccessHandler authenticationSuccessHandler; 

@Autowired 
private AuthenticationFailureHandler authenticationFailureHandler; 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .csrf() 
      .ignoringAntMatchers(publicUrls) 
      .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and() 
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 
      .exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and() 
      .addFilterBefore(jwtAuthenticationTokenFilter(), BasicAuthenticationFilter.class) 
      .authorizeRequests() 
      .anyRequest() 
      .authenticated().and() 
      .formLogin() 
      .loginPage("/api/login") 
      .successHandler(authenticationSuccessHandler) 
      .failureHandler(authenticationFailureHandler).and() 
      .logout() 
      .logoutRequestMatcher(new AntPathRequestMatcher("/api/logout")) 
      .logoutSuccessHandler(logoutSuccess) 
      .deleteCookies(TOKEN_COOKIE); 

} 

} 

这里是我的控制器:

@RestController 
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE) 
public class UserController { 

@Autowired 
private UserService userService; 
@Autowired 
private EmailService emailService; 
@Autowired 
private AuthorityRepository authorityRepository; 
@Autowired 
private PasswordEncoder passwordEncoder; 

@RequestMapping(method = GET, value = "/user/{userId}") 
public User loadById(@PathVariable Long userId) { 
    return this.userService.findById(userId); 
} 

@RequestMapping(method = GET, value= "/user/all") 
public List<User> loadAll() { 
    return this.userService.findAll(); 
} 

@RequestMapping(value = "/register", method = POST) 
public ResponseEntity<?> register(User user,HttpServletRequest request) throws UsernameInUseException{ 

    if (userService.findByUsername(user.getUsername()) != null) { 
     throw new UsernameInUseException(); 
    } 

    user.setEnabled(false); 
    user.setAccountNonExpired(true); 
    user.setAccountNonLocked(true); 
    user.setCredentialsNonExpired(true); 
    user.setConfirmationToken(UUID.randomUUID().toString()); 
    user.setPassword(passwordEncoder.encode(user.getPassword())); 

    return new ResponseEntity<>(user, HttpStatus.CREATED); 
} 

这是从我的角度2应用程序中的POST方法:

login(user) { 
const body = `username=${user.username}&password=${user.password}&email=${user.email}`; 
const headers = new Headers(); 
headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
return this.apiService.post(this.config.login_url, body, headers); 
} 

register(user) { 
const body = `username=${user.username}&password=${user.password}&email=${user.email}`; 
const headers = new Headers(); 
headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
return this.apiService.post(this.config.register_url, body, headers); 
} 

而且在我的角度2应用程序在app.codule.ts我也加了这条线

export function xsrfFactory() { 
return new CookieXSRFStrategy('myCookieName', 'My-Header-Name'); 
} 
providers:[ 
    { provide: XSRFStrategy, useFactory: xsrfFactory}, 
    ] 

任何意见和帮助,将不胜感激。

回答

0

我找到了一个方向。虽然不确定它是否安全,但现在它已经成功了。

在配置控制器

@EnableGlobalMethodSecurity(prePostEnabled = true) 

编辑这一行

@EnableGlobalMethodSecurity