gpt4 book ai didi

java - 由于授权无法访问API

转载 作者:行者123 更新时间:2023-12-02 11:06:14 25 4
gpt4 key购买 nike

我创建了自己的 api,以便在请求时为 UI 提供数据。不过,我使用 JHipster 实现 Spring Security 来验证 api 请求。当我登录到应用程序并使用 url (localhost:9090/api/lesson) 直接访问 api 时,它会为我的用户和管理员角色提供 401。

{
"type" : "https://www.jhipster.tech/problem/problem-with-message",
"title" : "Unauthorized",
"status" : 401,
"detail" : "Full authentication is required to access this resource",
"path" : "/api/lesson",
"message" : "error.http.401"
}

我检查了安全配置,路径/api/** 已设置为经过身份验证,这让我感到困惑,为什么如果登录我无法访问资源。

protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("api/lesson").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.apply(securityConfigurerAdapter());

}

虽然我的 API 不是像 JHipsters 那样创建的,比如使用 CrudRepository 而不是 JPA,但我认为这不会成为问题。不过,我可能是错的。

@RequestMapping("api/lesson")
@RestController
public class LessonAPI {

private final LessonService service;

public LessonAPI(@Autowired LessonService service){
this.service = service;
}

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Lesson> getAllLessons() {
return service.getAllLessons();
}

}

最佳答案

为什么你不使用如下内容:

http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/")
.permitAll()
.antMatchers("/api/auth/**","/api/user/exist")
.permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**", "/api/gift/**")
.permitAll()
.anyRequest()
.authenticated();

关于java - 由于授权无法访问API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com