繁体   English   中英

弹簧靴角2后方法403错误

[英]spring boot angular 2 post method 403 error

我有一个带有angular 2前端和spring boot后端的应用程序。 我正在通过遵循一个教程来启用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应用程序中的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的angular 2应用程序中,我还添加了这一行

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

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

我发现了一种方法。 尽管不确定它是否安全,但现在它确实成功了。

在配置控制器上

@EnableGlobalMethodSecurity(prePostEnabled = true)

将此行编辑为

@EnableGlobalMethodSecurity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM