我只想与角色“管理员”的用户能够得到“欢迎管理员信息:
@GetMapping("/admin")
public String admin() {
return "Welcome Admin!";
}
所以我补充说 .antMatchers("/admin").access("hasRole('ADMIN')")
到我的安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private JwtFilter jwtFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable().authorizeRequests()
.antMatchers("/authenticate", "/users/register","/products").permitAll()
.antMatchers("/admin").access("hasRole('ADMIN')") // HERE IT SHOULD CHECK FOR THE ADMIN ROLE
.anyRequest().authenticated().and().exceptionHandling()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);;
}
}
我用来访问的用户还具有admin角色:
但我总是得到403禁止作为回应:
而不是添加 .antMatchers("/admin").access("hasRole('ADMIN')")
对于我的securityconfig,我还尝试使用注解限制访问:
@PreAuthorize("hasRole('ROLE_ADMIN')")
//or @Secured({"ROLE_ADMIN"})
@GetMapping("/admin")
public String admin() {
return "Welcome Admin!";
}
但是我可以通过任何用户访问它,即使他们没有管理员角色(response status=200)。我做错什么了?
其他信息:
我的用户详细信息服务:
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = null;
try {
user = userRepository.findByName(username);
} catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}
if (user == null) {
return new org.springframework.security.core.userdetails.User(
" ", " ", true, true, true, true,
getAuthorities(Arrays.asList(
roleRepository.findByName("ROLE_USER"))));
}
return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles()));
}
private Collection<? extends GrantedAuthority> getAuthorities(
Collection<Role> roles) {
return getGrantedAuthorities(getPrivileges(roles));
}
private List<String> getPrivileges(Collection<Role> roles) {
List<String> privileges = new ArrayList<>();
List<Privilege> collection = new ArrayList<>();
for (Role role : roles) {
collection.addAll(role.getPrivileges());
}
for (Privilege item : collection) {
privileges.add(item.getName());
}
return privileges;
}
private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (String privilege : privileges) {
authorities.add(new SimpleGrantedAuthority(privilege));
}
return authorities;
}
public UserDetails loadUserByEmail(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), new ArrayList<>());
}
}
我的 jwtFilter.java
:
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private CustomUserDetailsService service;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("header:" + httpServletRequest.getHeader("Authorization"));
//get Authorization information from the request itself
String authorizationHeader = httpServletRequest.getHeader("Authorization");
String token = null;
String userName = null;
//check for its type, it must be Bearer + jwt
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
//get the token itself
token = authorizationHeader.substring(7);
//decrypt username
userName = jwtUtil.extractUsername(token);
}
if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = service.loadUserByUsername(userName);
if (jwtUtil.validateToken(token, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); // HERE IS THE getAuthorities function
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
我在一个额外的类中创建角色“admin”和“user”,并分配 privileges
如本教程所示。但事实上我从不需要特权,没有特权我就做不到,所以我把它们留在家里。因为没有特权,我不知道如何让授权进入我的用户详细信息,这是需要的 userDetails.getAuthorities()
功能在我的 jwtFilter
班级…:
@Component
public class SetupDataLoader implements
ApplicationListener<ContextRefreshedEvent> {
boolean alreadySetup = false;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PrivilegeRepository privilegeRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
if (alreadySetup)
return;
Privilege readPrivilege
= createPrivilegeIfNotFound("READ_PRIVILEGE");
Privilege writePrivilege
= createPrivilegeIfNotFound("WRITE_PRIVILEGE");
List<Privilege> adminPrivileges = Arrays.asList(
readPrivilege, writePrivilege);
createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
createRoleIfNotFound("ROLE_USER", Arrays.asList(readPrivilege));
Role adminRole = roleRepository.findByName("ROLE_ADMIN");
Role userRole = roleRepository.findByName("ROLE_USER");
User harald = new User();
harald.setName("Harald");
harald.setPassword(passwordEncoder.encode("test"));
harald.setEmail("test@test.com");
harald.setRoles(Arrays.asList(adminRole));
harald.setEnabled(true);
userRepository.save(harald);
User hartmut = new User();
hartmut.setName("Hartmut");
hartmut.setPassword(passwordEncoder.encode("test"));
hartmut.setEmail("test@test.com");
hartmut.setRoles(Arrays.asList(adminRole));
hartmut.setEnabled(true);
userRepository.save(hartmut);
}
alreadySetup = true;
}
@Transactional
Privilege createPrivilegeIfNotFound(String name) {
Privilege privilege = privilegeRepository.findByName(name);
if (privilege == null) {
privilege = new Privilege(name);
privilegeRepository.save(privilege);
}
return privilege;
}
@Transactional
Role createRoleIfNotFound(
String name, Collection<Privilege> privileges) {
Role role = roleRepository.findByName(name);
if (role == null) {
role = new Role(name);
role.setPrivileges(privileges);
roleRepository.save(role);
}
return role;
}
}
我的 Role.java
:
@Entity
@Table(name="roles")
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "roles_privileges",
joinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
public Role(String name) {
this.name = name;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
还有我的 privilege.java
:
@Entity
@Table(name="privileges")
@Data
@NoArgsConstructor
public class Privilege {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Privilege(String name) {
this.name = name;
}
@Override
public String toString() {
return "Privilege{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
2条答案
按热度按时间goucqfw61#
注解
public class SecurityConfig extends WebSecurityConfigurerAdapter
与@EnableGlobalMethodSecurity(prePostEnabled = true)
而且,new9mtju2#
1/您需要在安全配置中启用安全注解,并添加以下行:
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
预设让你使用@preauthorize,@postauthorize,etc和securedenabled以使用@secured2/为了说明只有具有admin角色的用户才能访问“/admin”,您需要添加如下注解:`
.antMatchers("/admin").access("hasRole('ADMIN')")
应该也可以,而不是使用注解。3/您需要确保您的方法loadbyusername在使用包含权限“role\u admin”的权限列表登录时返回用户admin。