此问题已在此处找到答案:
springboot安全角色不工作(3个答案)
两天前关门了。
我在SpringBoot项目中为SpringSecurity提供了以下文件。当我使用inmemoryauthentication时,它起作用,但当我使用CustomUserDetails服务时,它不起作用。自定义userdetailsservice类被调用,但仍然给出403(当我尝试访问/user时),但它适用于打开的URL(/usr)。
import org.springframework.security.core.userdetails.User
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//not using parameter which is being passed as trying to figure out the problem first.
UserDetails user = User.withUsername("abc").password("abc").authorities("ADMIN").build();
return user;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
// auth.inMemoryAuthentication().withUser("abc").password("abc").roles("ADMIN");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/user").hasRole("ADMIN")
.antMatchers("/").permitAll()
.and().formLogin();
}
}
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/usr")
public ResponseEntity<String> getOpenResponse() {
return ResponseEntity.ok("You are accessing open url");
}
@GetMapping("/user")
public ResponseEntity<String> getSecuredResponse() {
return ResponseEntity.ok("You are accessing secured path");
}
}
我做错了什么?我错过什么了吗?
1条答案
按热度按时间8wigbo561#
问题在于:
您将用户权限设置为
"ADMIN"
,但在SecurityConfig
类,您希望用户拥有一个角色"ADMIN"
事实上,这是一个权威的捷径"ROLE_ADMIN"
:要解决此问题,应定义用户角色: