当前位置: 首页 > 面试题库 >

无法在Spring Security中使用@Secured Method Security批注

汝吕恭
2023-03-14
问题内容

我做了很多研究,对我来说一切看起来都不错……但是我无法使它正常工作!有人知道吗?

不管我做什么,相关的映射对任何人都保持公开状态(无论匿名或登录,无论他们扮演什么角色)。

理想情况下,我希望所有请求都公开,但@Secured()注释的请求除外-显然,只有具有特定角色的用户才能访问这些映射。

那可能吗?

仅供参考,我目前构建了一种方法“ hasRole(String
role)”,该方法检查登录用户的角色,如果该方法返回false,则抛出NotAuthorizedException(定制)。

用户详细信息

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {

      List<GrantedAuthority> grantedAuthorities = null;

      System.out.print("Account role... ");
      System.out.println(account.getRole());

      if (account.getRole().equals("USER")) {
          GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
          grantedAuthorities = Arrays.asList(grantedAuthority);
      }

      if (account.getRole().equals("ADMIN")) {
          GrantedAuthority grantedAuthorityUser = new SimpleGrantedAuthority("ROLE_USER");
          GrantedAuthority grantedAuthorityAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
          grantedAuthorities = Arrays.asList(grantedAuthorityUser, grantedAuthorityAdmin);
      }

      return grantedAuthorities;
  }

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthFailure authFailure;

    @Autowired
    private AuthSuccess authSuccess;

    @Autowired
    private EntryPointUnauthorizedHandler unauthorizedHandler;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /*@Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }*/

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }

  private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
  }

    @Override
    public void configure(HttpSecurity http) throws Exception {
      http.csrf().csrfTokenRepository(csrfTokenRepository())
        .and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and().formLogin().loginPage("/login").successHandler(authSuccess).failureHandler(authFailure)
        //.and().authorizeRequests().antMatchers("/rest/**").authenticated()
        //.and().authorizeRequests().antMatchers("/**").permitAll()
        .and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);;
    }

AccountController

  @Secured("ROLE_USER")
  @RequestMapping(method = RequestMethod.GET)
  public List<Account> getAllAccounts(@RequestParam(value = "mail", required = false) String mail) {

谢谢!


问题答案:

您可以通过Spring HttpSecurity使用Controller范围的Security。尝试将其添加到您的configure方法中:

.antMatchers("rest/accounts*").hasRole("ADMIN")

如果您希望任何要求公开(真的吗?):

.anyRequest().permitAll()

当您从任何地方访问它时,还可以在UserDetailsS​​ervice中保护示例的Methodinvocation:

@Secured("ROLE_USER")
public getAllAccounts(...){...}

只有这样,您才需要使用以下方法注释SecurityConfig:

@EnableGlobalMethodSecurity(securedEnabled = true)

实际上,我们建议您在服务层使用方法安全性来控制对应用程序的访问,并且不要完全依赖于在Web应用程序级别定义的安全性约束的使用。URL会发生变化,很难考虑到应用程序可能支持的所有可能的URL以及如何处理请求。您应该尝试限制自己使用一些简单易懂的简单蚂蚁路径。始终尝试使用“默认拒绝”方法,在此方法中,您最后定义了一个全包通配符(/或),并拒绝访问。在服务层定义的安全性更健壮,更难绕开,因此您应始终利用Spring
Security的方法安全性选项。

参见:http :
//docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-
SNAPSHOT/reference/htmlsingle/#request-
matching



 类似资料:
  • 首次使用配置文件并需要帮助。我有一个抽象基类(决策管理规则演示器),它通过注释连接其依赖项(规则处理程序)。 当我使用“最”的配置文件运行时,我希望“ITestRuleHandler”是“规则处理程序”的子级。“伊斯特规则手”在哪里 我在日志中看到活动配置文件是“itest” 我在贴接线的日志 处理bean'vendorServiceRuleExector'的注入元素: AutowiredFiel

  • 我正在学习springsecurity(基于java的配置),我无法使注销正常工作。当我点击注销时,我看到URL更改为http://localhost:8080/logout并获取“HTTP 404-/logout”。登录功能工作正常(即使使用自定义登录表单),但问题是注销,我怀疑重定向的url“localhost:8080/logout”应该类似于“localhost:8808/springte

  • 我有一个AS3/gradle plugin 3项目,我们最近在其中引入了一个本地简单的注释处理器。适用于gradles annotationProcessor Dependency指令。 我开始添加Kotlin代码,并将所有annotationProcessor指令移动到kapt指令。Glide和logan square对Kotlin使用注释处理器没有问题,但我们当地的AP项目无法由kapt执行:

  • 我想通过.properties文件配置bean字符串字段。但它并不替换值键,这意味着它回显“${value}”字符串。我的代码如下:

  • 问题内容: 我正在研究要与Jenkins 2.0一起使用的Jenkinsfile。无法识别该方法。我缺少一些配置以使其可用吗? 我的Jenkinsfile: 运行时,出现以下错误: among [AWSEBDeployment, archive, bat, build, catchError, checkout, deleteDir, dir, echo, emailext, error, fil