我创建了自己的api来为UI提供数据请求。但是我使用的是实现Spring Security的JHipster来验证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/**已设置为authenticated,这就是为什么登录后我无法访问资源的原因。
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();
}
}
2条答案
按热度按时间epfja78i1#
为什么您不使用以下内容:
wfauudbj2#
添加这一行,您的所有/api/* 资源都将是公共的。