Java Spring Security-401未经授权访问

Java Spring Security-401未经授权访问,java,spring,spring-security,jwt,Java,Spring,Spring Security,Jwt,我创建了一个表单,将数据发送到我的后端,后端将数据持久化到数据库中 只要我的antMatcher上有.permitAll(),它就可以正常工作,但当我尝试保护它,以便只有管理员可以进行该调用(DB中的admin角色是role_admin)时,它会返回401个未经授权的访问,而不返回任何消息。我试过了 .hasRole(“管理员”) .hasRole(“角色管理”) .hasAuthority(“管理”) .hasAuthority(“角色\管理”) 它们都不起作用。 我的请求如下(发布标

我创建了一个表单,将数据发送到我的后端,后端将数据持久化到数据库中

只要我的antMatcher上有.permitAll(),它就可以正常工作,但当我尝试保护它,以便只有管理员可以进行该调用(DB中的admin角色是role_admin)时,它会返回401个未经授权的访问,而不返回任何消息。我试过了

  • .hasRole(“管理员”)
  • .hasRole(“角色管理”)
  • .hasAuthority(“管理”)
  • .hasAuthority(“角色\管理”)
它们都不起作用。

我的请求如下(发布标题):

我的SecurityConfig类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
    securedEnabled = true,
    jsr250Enabled = true,
    prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UserDetailsServiceImpl userDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
    return new JwtAuthenticationFilter();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/",
                    "/favicon.ico",
                    "/**/*.png",
                    "/**/*.gif",
                    "/**/*.svg",
                    "/**/*.jpg",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js")
                    .permitAll()
                .antMatchers("/api/auth/**")
                    .permitAll()
                .antMatchers("/api/book/**")
                    .permitAll()
                .antMatchers("/api/author/**")
//                        .permitAll()
                    .hasAnyRole("ROLE_ADMIN", "ADMIN", "ROLE_USER", "USER", "ROLE_ROLE_ADMIN", 
"ROLE_ROLE_USER")
            .anyRequest()
            .authenticated();

    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
我的UserDetailsServiceImpl类:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String email)
        throws UsernameNotFoundException {
    User user = userRepository.findByEmail(email);

    return UserDetailsImpl.create(user);
}

@Transactional
public UserDetails loadUserById(Integer id) {
    User user = userRepository.findById(id).orElseThrow(
            () -> new UsernameNotFoundException("User not found with id: " + id)
    );

    return UserDetailsImpl.create(user);
}
}
我的JwtAuthenticationEntryPoint类:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);

@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 
AuthenticationException e) throws IOException, ServletException {
    logger.error("Unauthorized access. Message:", e.getMessage());
    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}
我的JwtAuthenticationFilter:

public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Autowired
private JwtTokenProvider tokenProvider;

@Autowired
private UserDetailsServiceImpl userDetailsService;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);


@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse 
httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    try {
        String jwt = getJwtFromRequest(httpServletRequest);

        if(StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            Integer userId = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = userDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authentication = new 
UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

            authentication.setDetails(new 
WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
        }
    } catch (Exception e) {
        logger.error("Could not set user authentication in security context", e);
    }

    filterChain.doFilter(httpServletRequest, httpServletResponse);
}

private String getJwtFromRequest(HttpServletRequest request) {
    String bearerToken = request.getHeader("Authorization");
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
}
正确检查JWT令牌的有效性。这不是当前的问题。 感谢您的帮助

编辑: 添加了UserDetailsImpl的实现:

public class UserDetailsImpl implements UserDetails {
private Integer id;

@JsonIgnore
private String email;

private String name;

@JsonIgnore
private String password;

private boolean isAdmin;

private Collection<? extends GrantedAuthority> authorities;

public UserDetailsImpl(Integer id, String email, String name, String 
password, boolean isAdmin, Collection<? extends GrantedAuthority> 
authorities) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.password = password;
    this.authorities = authorities;
    this.isAdmin = isAdmin;
}

public static UserDetailsImpl create(User user) {
    List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
            new SimpleGrantedAuthority(role.getName().name())
    ).collect(Collectors.toList());

    boolean isAdmin = false;

    for(Role role:  user.getRoles()) {
        if(RoleName.ROLE_ADMIN.equals(role.getName())) {
            isAdmin = true;
        }
    }

    return new UserDetailsImpl(
            user.getId(),
            user.getEmail(),
            user.getName(),
            user.getPassword(),
            isAdmin,
            authorities
    );
}

public Integer getId() {
    return id;
}

public String getName() {
    return name;
}

@Override
public String getUsername() {
    return email;
}

@Override
public String getPassword() {
    return password;
}

public boolean isAdmin() {
    return isAdmin;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    UserDetailsImpl that = (UserDetailsImpl) o;
    return Objects.equals(id, that.id);
}

@Override
public int hashCode() {

    return Objects.hash(id);
}
public类userdetailsiml实现UserDetails{
私有整数id;
@杰索尼奥雷
私人字符串电子邮件;
私有字符串名称;
@杰索尼奥雷
私有字符串密码;
私有布尔isAdmin;

私人收藏我发现您没有更新
SecurityContextHolder
。无法将其放入注释中,因此我将其写在这里

authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest))
SecurityContextHolder.getContext().setAuthentication(authentication); //this seems missing

您的用户是否具有管理员角色?您是否可以共享UserDetailsImpl.create()的实现?可能您当时没有授予适当的角色和权限您能否向我们展示
userDetails.GetAuthories()的输出内容
is?@tashkhhisi据我所知,是的,它应该有它。@Youri我在文章末尾添加了.getauthorities after.create(user)的实现和输出。哦,JwtAuthenticationFilter类中缺少它。我会看看这是否奏效。