[英]Error: Full authentication is required to access this resource when using @PreAuthorize
I am trying to implement a authentication using Spring Boot, JWT with Roles我正在尝试使用 Spring Boot、JWT with Roles 实现身份验证
I have the error:我有错误:
full authentication is required to access this resource
访问此资源需要完整身份验证
when send POST request to "http://localhost:8080/api/profile/edit_user_detail" (with authoziration header)将POST请求发送到“http://localhost:8080/api/profile/edit_user_detail”(带有授权标头)时
Below is my Controller下面是我的控制器
@Controller
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api/profile")
public class UserAPI {
@Autowired
UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
QARepository qaRepository;
@Autowired
DiscussRepository discussRepository;
@Autowired
AnnouncementRepository announcementRepository;
@PostMapping(value = {"/edit_user_detail"})
@PreAuthorize("hasRole('ROLE_USER')")
public ResponseEntity<?> editInfo(@RequestBody Map map) throws ParseException {
String username = map.get("username").toString();
String display_name = map.get("display_name").toString();
User user = userRepository.findByUserName(username).get(0);
user.setuDigitalName(display_name);
userRepository.save(user);
return ResponseEntity.ok("Updated");
}
But when i remove the line但是当我删除该行时
@PreAuthorize("hasRole('ROLE_USER')")
@PreAuthorize("hasRole('ROLE_USER')")
then i can success POST the request and edited successfully the user (I have checked in database)然后我可以成功发布请求并成功编辑用户(我已经检查了数据库)
Also this is my EntryPoint (to catch Exception)这也是我的入口点(捕捉异常)
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger log = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
log.error("Authorized error: " + e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Error: Unauthorized");
e.printStackTrace();
}
}
And this is my Configuration file这是我的配置文件
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ConfigAuthenticate extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServices userDetailsServices;
@Autowired
private AuthEntryPointJwt unauthorizeHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter(){
return new AuthTokenFilter();
}
@Bean
@Override public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServices).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizeHandler)
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
I think there are a problem with configuration in WebSecurityConfigurerAdapter , i have try to我认为WebSecurityConfigurerAdapter 中的配置有问题,我已尝试
@PreAuthorize("hasRole('ROLE_USER')")
to @PreAuthorize("hasRole('USER')")
@PreAuthorize("hasRole('ROLE_USER')")
改为@PreAuthorize("hasRole('USER')")
but it's still not work, anybody have solution但它仍然不起作用,任何人都有解决方案
Try removing .antMatchers("/**").permitAll()
, and add these lines to your:尝试删除
.antMatchers("/**").permitAll()
,并将这些行添加到您的:
application.yml应用程序.yml
logging:
level:
org.springframework.security: TRACE
or application.properties或 application.properties
logging.level.org.springframework.security=TRACE
And you could see the information about your user like this:您可以像这样看到有关您的用户的信息:
AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]
You can rely on Granted Authorities
in order to determine user's roles您可以依靠
Granted Authorities
来确定用户的角色
Because you're setting .antMatchers("/**").permitAll()
before .anyRequest().authenticated()
, I'm not so sure whether you validated the user successfully or not.因为您在
.antMatchers("/**").permitAll()
之前设置了.antMatchers("/**").permitAll()
.anyRequest().authenticated()
,所以我不确定您是否成功验证了用户。 If not, then the AnonymousAuthenticationFilter
will create an anonymous user for you.如果没有,那么
AnonymousAuthenticationFilter
将为您创建一个匿名用户。 And in case you don't add @PreAuthorize("hasRole('USER')")
, the FilterSecurityInterceptor
, bases on .antMatchers("/**").permitAll()
, will allow the request gets through it and accesses the controller.如果您不添加
@PreAuthorize("hasRole('USER')")
,基于.antMatchers("/**").permitAll()
的FilterSecurityInterceptor
将允许请求通过它并访问控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.