【问题标题】:Accessing secure resource with spring resource使用 spring 资源访问安全资源
【发布时间】:2019-02-04 13:41:56
【问题描述】:

我正在尝试将 Spring Security 集成到我的应用程序中,但出于某种原因(我不知道),我在每次请求时都会收到 403 错误。我确信这与弹簧安全有关。以下是我的代码的 sn-p 以了解更多详细信息。

这是我第一次尝试将 Spring Security 集成到我的应用程序中,因此我可能会遗漏一些东西。

我的 WebSecurity 课程中有这个

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private JwtTokenProvider jwtTokenProvider;

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

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic().disable()
            .csrf().disable()
            .cors().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers( HttpMethod.POST, "/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider));
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}

在我的控制器中我有这个

@RestController
@RequestMapping("/auth")
public class LoginController {
@Autowired
private UserService userService;

@RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public Response<UserDto> register(@RequestBody Request<UserDto> request){
    MessengerUser user = userService.saveUser(request.getData());
    return new Response<>(new ModelMapper().map(user, UserDto.class));
}

@RequestMapping(value = "/sign-in", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public Response<LoginDto> signin(@RequestBody Request<UserDto> request) {
    LoginDto loginDto = userService.authenticateUser(request.getData());
    return new Response<>(loginDto);
   }
}

根据我的要求 { “数据”:{ “用户名”:“用户名”, “密码”:“密码” } }

我怀疑这与我的配置有关,但我不确定还有什么可以尝试的。

【问题讨论】:

  • 您如何称呼您的端点?可以显示请求地址吗?
  • 据我了解 JWT,您应该在每个请求中发送授权令牌(在成功的用户授权/登录后获得)。你这样做吗?
  • 我知道我的问题是什么。在花了很长时间之后,我意识到我的 HTTP 请求设置不正确。我的愚蠢错误

标签: java spring-boot spring-security


【解决方案1】:

事实证明,这是我的错误。我有错误的请求类型,这是我的愚蠢错误。

一切都正确,但请求类型是 GET 而不是 POST

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 2015-09-18
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多