У меня есть токен доступа oauth, и я пытаюсь получить доступ к защищенному ресурсу, которому требуется роль ADMIN. Но он показывает мне ошибку 403.
Я настроил SecurityConfiguration как hasAnyRole ("ROLE_ADMIN") Моя БД имеет значение роли как ROLE_ADMIN. Он не попадает в метод RestController. Когда я настраиваю с помощью разрешенияAll (), он работает. Я пытаюсь вызвать метод findAllusers в контроллере
, прикрепив коды ниже. Может ли кто-нибудь помочь решить эту проблему?
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService =userDetailsService;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().
antMatchers(HttpMethod.POST, "/user/**").permitAll().
antMatchers(HttpMethod.POST,"/admin/**").hasAnyRole("ROLE_ADMIN").
antMatchers(HttpMethod.POST,"/admin**").hasAnyRole("ROLE_ADMIN").
anyRequest().authenticated();
}
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select usrnam as username,usrpwd as password, case when usrsta='A' then true else false end as enabled from usrmst where usrnam=?")
.authoritiesByUsernameQuery("select usrnam as username,usrtyp as role from usrmst where usrnam=?");
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}}
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer serverSecurityConfigurer) {
serverSecurityConfigurer.resourceId("api");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.antMatcher("/api/**")
.authorizeRequests()
.antMatchers("/user**").permitAll()
.antMatchers("/user/**").permitAll()
.antMatchers("/admin**").hasAuthority("ROLE_ADMIN")
.antMatchers("/api/**").authenticated()
.and().authorizeRequests().anyRequest().access("#oauth2.hasScope('read')");
}}
@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)
.authorities("ROLE_ADMIN")
.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;
}}
@RestController
public class UserController {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
@PostMapping("/admin/findAllUsers")
public List<User> findAllUsers() {
System.out.println("entering findAllUsers");
return userRepository.findAll();
}}