spring boot angular 2 post方法403错误

时间:2017-08-16 00:49:43

标签: angular spring-boot spring-security csrf

我有一个角度为2的前端和弹簧启动后端的应用程序。我正在使用Spring boot security csrf,通过遵循教程并希望保持这种方式。当我从angular 2应用程序发布用户注册请求时,我正面临的问题我得到403禁止错误。但是使用登录POST方法可以正常工作。

这是我的spring boot安全配置:

@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);
}

这是我的angular 2 app的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);
}

在app.codule.ts的我的角度2应用程序中,我也添加了这一行

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

任何建议和帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

在配置控制器上

@EnableGlobalMethodSecurity(prePostEnabled = true)

将此行编辑为

@EnableGlobalMethodSecurity