SpringBoot OAuth2错误“访问此资源需要完整身份验证”

时间:2020-07-05 09:23:43

标签: spring-boot authentication oauth-2.0 authorization

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

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

class UserManager():
    email = "abc"
    def create_user(email, password=None):
        user = (email, password)

    def create_superuser(email, password):
        user = create_user(
            email,
            password = password
            )
        return ("User is an admin")

password = input("Password: ")

User = UserManager()

print(User.create_superuser(password))

我正在使用邮递员进行测试,只是尝试获取数据库中的所有用户。当我打电话时,控件没有到达RestController。我只想获取用户列表,并提供了allowAll()。

有人可以帮忙吗? 我在下面发布代码。

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}
@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=?");
  }
}
@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();
    }
}
@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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/user**").permitAll()
            .antMatchers("/user/**").permitAll()
            .antMatchers("/admin**").hasAuthority("ADMIN")
            .antMatchers("/api/**").authenticated()
            .anyRequest().authenticated();