spring boot angular 2 post方法403错误
Posted
技术标签:
【中文标题】spring boot angular 2 post方法403错误【英文标题】:spring boot angular 2 post method 403 error 【发布时间】:2018-01-24 00:05:50 【问题描述】:我有一个带有 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,
]
我们将不胜感激任何建议和帮助。
【问题讨论】:
【参考方案1】:我找到了一种方法。虽然不确定它是否安全,但它现在就成功了。
在配置控制器上
@EnableGlobalMethodSecurity(prePostEnabled = true)
将此行编辑为
@EnableGlobalMethodSecurity
【讨论】:
以上是关于spring boot angular 2 post方法403错误的主要内容,如果未能解决你的问题,请参考以下文章
Angular 2 + CORS + 带有 Spring Security 的 Spring Boot Rest Controller
maven - Spring Boot/Angular 2/4 项目战构建
Spring Boot + Angular 2 Heroku 部署