我已在我的应用中配置了spring security,身份验证工作正常,但授权不起作用意味着@secured()
注释无法正常工作。我在访问网址时遇到错误"出现意外错误{ {1}}。
访问被拒绝"。
我的春季配置是
(type=Forbidden, status=403)
我的控制器是
@Autowired
private MongoDBAuthenticationProvider authenticationProvider;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().defaultSuccessUrl("/resource")
.and().logout().and().authorizeRequests()
.antMatchers("/logout").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
.and().csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
数据库用户
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@Secured(value={"ROLE_ADMIN"})
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public void getUser() {
System.out.println("working");
}
}
我的mongodb身份验证提供程序
{ "_id" : ObjectId("555982a5360403572551660c"), "username" : "user", "password" : "pass", "role" : "ADMIN" }
用户域
@Service
public class MongoDBAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
@Autowired
MongoUserDetailsService mongoUserDetailsService;
@Autowired MongoTemplate mongoTemplate;
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
UserDetails loadedUser;
try {
loadedUser = mongoUserDetailsService.loadUserByUsername(username);
} catch (Exception repositoryProblem) {
throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
}
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
}
}
答案 0 :(得分:0)
在Spring Security Config File中添加此bean
@Bean
public RoleVoter roleVoter() {
RoleVoter roleVoter = new RoleVoter();
roleVoter.setRolePrefix("");
return roleVoter;
}
并编写像这样的安全注释
@Secured(value={"ADMIN"})
答案 1 :(得分:0)
@Secured(value={"ADMIN"})
代替
@Secured(value={"ROLE_ADMIN"})
您也可以尝试
@PreAuthorize("hasRole('ADMIN')")
如果@Secured注释仍然不起作用