2 回答
TA贡献1831条经验 获得超4个赞
Spring已经有了这个,只需添加到您的配置中,并使用特殊注释等注释您的安全方法:@EnableGlobalMethodSecurity(prePostEnabled = true)@PreAuthorize("isAuthenticated()")@PreAuthorize("hasAnyRole('ADMIN)")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConf43547 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
....
}
}
和控制器中
@GetMapping("/test")
@PreAuthorize("isAuthenticated()") //this annotation better add to service method @Service
public String test() {
return "abc"
}
或 import org.springframework.security.core.Authentication;
@GetMapping("/test")
public String getOk(Authentication authentication) {
return authentication.getName();
}
TA贡献1815条经验 获得超6个赞
我决定它的问题,所以:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public CurrentUserMethodArgumentResolver userMethodArgumentResolver() {
return new CurrentUserMethodArgumentResolver() {
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
SecurityContext securityContext = SecurityContextHolder.getContext();
CurrentUser annotation = parameter.getParameterAnnotation(CurrentUser.class);
boolean anonymousUser = securityContext.getAuthentication() instanceof AnonymousAuthenticationToken;
if (annotation.required() && anonymousUser) {
throw new BadCredentialsException("access is denied");
}
return super.resolveName(name, parameter, request);
}
};
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
list.add(userMethodArgumentResolver());
super.addArgumentResolvers(list);
}
添加回答
举报