首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SpringBoot OAuth2错误“需要完全身份验证才能访问此资源”

SpringBoot OAuth2错误“需要完全身份验证才能访问此资源”
EN

Stack Overflow用户
提问于 2020-07-05 17:23:44
回答 1查看 34关注 0票数 0

我正在尝试实现OAuth2 - SpringBoot身份验证。

我已经使用permitAll()配置了一个路径,但是即使配置了它,它也会显示错误

代码语言:javascript
运行
复制
{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

我正在使用postman进行测试,并简单地尝试获取数据库中的所有用户。当我调用时,控件不会出现在RestController中。我只想获得用户列表,并且提供了permitAll()。

有人能帮帮忙吗?我发布了下面的代码。

代码语言:javascript
运行
复制
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  DataSource dataSource;

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

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests().
        antMatchers(HttpMethod.POST, "/api/**").permitAll().
        antMatchers(HttpMethod.POST,"/admin/**").hasAnyRole("ADMIN").
        anyRequest().authenticated();

  }

  @Override
  public void configure(AuthenticationManagerBuilder builder) throws Exception{
    builder.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select usrnam,usrpwd, case when usrsta='A' then true else false end from chsusrmst where usrnam=?")
        .authoritiesByUsernameQuery("select usrnam,usrtyp from chsusrmst where usrnam=?");
  }
}
代码语言:javascript
运行
复制
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;


    @PostMapping("/user/register")
    public String register(@RequestBody User user) {

        String encodedPassword = passwordEncoder.encode(user.getUserPassword());
        user.setUserPassword(encodedPassword);
        userRepository.save(user);
        return "User created";
    }

    @PostMapping("/admin/findUser")
    public User findUser(@RequestBody User user) {

        return userRepository.findByUserName(user.getUserName());
    }

    @PostMapping("/user/findAllUsers")
    public List<User> findAllUsers() {

        return userRepository.findAll();
    }
}
代码语言:javascript
运行
复制
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final PasswordEncoder passwordEncoder;
    private final UserDetailsService userDetailsService;

    @Value("${jwt.clientId:client}")
    private String clientId;

    @Value("${jwt.client-secret:secret}")
    private String clientSecret;

    @Value("${jwt.signing-key:123}")
    private String jwtSigningKey;

    @Value("${jwt.accessTokenValidititySeconds:43200}") // 12 hours
    private int accessTokenValiditySeconds;

    @Value("${jwt.authorizedGrantTypes:password,authorization_code,refresh_token}")
    private String[] authorizedGrantTypes;

    @Value("${jwt.refreshTokenValiditySeconds:2592000}") // 30 days
    private int refreshTokenValiditySeconds;

    public AuthorizationServerConfig(AuthenticationManager authenticationManager, PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.passwordEncoder = passwordEncoder;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(clientId)
                .secret(passwordEncoder.encode(clientSecret))
                .accessTokenValiditySeconds(accessTokenValiditySeconds)
                .refreshTokenValiditySeconds(refreshTokenValiditySeconds)
                .authorizedGrantTypes(authorizedGrantTypes)
                .scopes("read", "write")
                .resourceIds("api");
    }
    

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .accessTokenConverter(accessTokenConverter())
                .userDetailsService(userDetailsService)
                .authenticationManager(authenticationManager);
    }

    @Bean
    JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        return converter;
    }
}
代码语言:javascript
运行
复制
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

   

    @Override
    public void configure(ResourceServerSecurityConfigurer serverSecurityConfigurer) {
        serverSecurityConfigurer.resourceId("api");
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-07-05 20:47:26

感谢您的考虑。我找到问题了。资源服务器中缺少HttpSecurity配置,已通过添加以下部分解决此问题。

代码语言:javascript
运行
复制
http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/user**").permitAll()
            .antMatchers("/user/**").permitAll()
            .antMatchers("/admin**").hasAuthority("ADMIN")
            .antMatchers("/api/**").authenticated()
            .anyRequest().authenticated();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62738921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档