【发布时间】:2021-09-27 19:28:03
【问题描述】:
我正在使用 Spring MVC。
@Secured 注释不起作用。
我尝试了很多选项,但似乎没有任何效果。告诉我,我做错了什么?
我正在查看此页面 - Spring Security, Method Security annotation (@Secured ) is not working (java config) 它对我没有帮助。
。 . .
这是我的 github 代码。 https://github.com/MyTestPerson/securede
Personal.class
@Controller
public class Personal {
@GetMapping(value = "/personal")
public ModelAndView personalGet () {
ModelAndView modelAndView = new ModelAndView("/personal");
modelAndView.addObject("msg", myMsg());
return modelAndView;
}
@Secured(value = {"ROLE_ADMIN"})
private String myMsg() {
return "Hello USER!!!";
}
}
SecurityConfig.class
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers("/").permitAll()
.mvcMatchers("/personal/**").hasAnyRole("ADMIN","USER")
.mvcMatchers("/login").anonymous()
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}
}
RootConfig.class
@EnableWebMvc
@Configuration
@ComponentScan("com.securede.security")
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class RootConfig implements WebMvcConfigurer {
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
UserDetail.class
@Service
public class UserDetail implements UserDetailsService {
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return new org.springframework.security.core.userdetails.User(
"user",
passwordEncoder.encode("user"),
true,
true,
true,
true,
getAuthorities());
}
private Collection<? extends GrantedAuthority> getAuthorities(){
List<SimpleGrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
return authList;
}
}
【问题讨论】:
标签: java spring spring-mvc spring-security