无法获取@Secured方法安全注解春季安全工作 [英] Can not get the @Secured Method Security annotations working in Spring Security

查看:372
本文介绍了无法获取@Secured方法安全注解春季安全工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了很多的研究,对我一切看起来正确的......但我不能得到这个工作!任何人有任何想法?

不管我做什么,相关的映射仍然公开向任何人(匿名或登录,无论他们有什么样的角色)。

我非常希望拥有的所有请求是公开的,除了那些由@Secured(注释) - 明明只有与特定角色的用户将被允许访问这些映射

这可能吗?

FYI作为一种解决方法目前我建造了检查的作用的方法hasRole(字符串角色)已登录的用户,并抛出一个NotAuthorizedException(定制),如果该方法返回false。

的UserDetails

  @覆盖
  公文集&LT ;?扩展的GrantedAuthority> getAuthorities(){      清单<&GrantedAuthority的GT; grantedAuthorities = NULL;      System.out.print(帐户的角色......);
      的System.out.println(account.getRole());      如果(account.getRole()。等于(USER)){
          GrantedAuthority的一个GrantedAuthority =新SimpleGrantedAuthority(ROLE_USER);
          grantedAuthorities = Arrays.asList(的GrantedAuthority);
      }      如果(account.getRole()。等于(ADMIN)){
          的GrantedAuthority grantedAuthorityUser =新SimpleGrantedAuthority(ROLE_USER);
          的GrantedAuthority grantedAuthorityAdmin =新SimpleGrantedAuthority(ROLE_ADMIN);
          grantedAuthorities = Arrays.asList(grantedAuthorityUser,grantedAuthorityAdmin);
      }      返回grantedAuthorities;
  }

SecurityConfig

  @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled =真)
公共类SecurityConfig扩展WebSecurityConfigurerAdapter {    @Autowired
    私人AuthFailure authFailure;    @Autowired
    私人AuthSuccess authSuccess;    @Autowired
    私人EntryPointUnauthorizedHandler unauthorizedHandler;    @Autowired
    私人UserDetailsS​​erviceImpl的UserDetailsS​​ervice;    / * @自动装配
    公共无效configAuthBuilder(AuthenticationManagerBuilder建设者)抛出异常{
        builder.userDetailsS​​ervice(UserDetailsS​​ervice的);
    } * /    @覆盖
    公众的AuthenticationManager authenticationManagerBean()抛出异常{
        返回super.authenticationManagerBean();
    }    @Autowired
    @覆盖
    公共无效配置(AuthenticationManagerBuilder建设者)抛出异常{
        builder.userDetailsS​​ervice(UserDetailsS​​ervice的);
    }  私人CsrfTokenRepository csrfTokenRepository(){
    HttpSessionCsrfTokenRepository库=新HttpSessionCsrfTokenRepository();
    repository.setHeaderName(X-XSRF-TOKEN);
    返回库;
  }    @覆盖
    公共无效配置(HttpSecurity HTTP)抛出异常{
      http.csrf()。csrfTokenRepository(csrfTokenRepository())
        。而()。exceptionHandling()的AuthenticationEntryPoint(unauthorizedHandler)
        。而()。formLogin()。loginPage(/登录)。successHandler(authSuccess).failureHandler(authFailure)
        //和()。authorizeRequests()。antMatchers(/ REST / **)。验证()
        //和()。authorizeRequests()。antMatchers(/ **)。permitAll()
        。而()。addFilterAfter(新CsrfHeaderFilter(),CsrfFilter.class);;
    }

的AccountController

  @Secured(ROLE_USER)
  @RequestMapping(方法= RequestMethod.GET)
  公开名单<&帐户GT; getAllAccounts(@RequestParam(值=邮件,要求= FALSE)字符串的邮件){

谢谢!


解决方案

您可以使用控制器范围的安全与Spring HttpSecurity。尝试添加到您的配置方法:

  .antMatchers(休息/账户*)。hasRole(ADMIN)

如果你希望的任何请求是公共的(真的吗?)

  .anyRequest()。permitAll()

您还可以保护您的MethodInvocation例在你的UserDetailsS​​ervice当您从任何地方访问它:

  @Secured(ROLE_USER)
公共getAllAccounts(...){...}

只有这样,你必须注释你的SecurityConfig:

  @EnableGlobalMethodSecurity(securedEnabled =真)


  

在实践中,我们建议您为您服务使用方法的安全性
  层,控制访问你的应用程序,也不要完全依赖
  对使用在Web应用程序中定义的安全约束
  水平。网址改变并且难以采取的帐户中的所有
  可能的网址的应用程序可能支持和要求如何可能
  进行操作。你应该尝试限制自己使用一些
  简单的蚂蚁路径这是很容易理解。总是尝试使用
  一个拒绝按默认的方式,你有一个包罗万象的通配符(/或
  )定义的最后的,拒绝访问。在服务定义的安全
  一层是更强大和难以绕过,所以你应该总是
  利用Spring Security的方法安全选项的优势。


请参见:<一href=\"http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#request-matching\" rel=\"nofollow\">http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#request-matching

I have done a lot of Research and to me everything looks right... but I cannot get this to work! Anyone has any idea?

No matter what I do, the relevant mapping remains public to anyone (anonymous or logged in, no matter what Role they have).

Ideally I would like to have ALL requests to be Public, except those which are annotated by @Secured() - obviously only the users with the specific roles would be allowed access to these mappings.

Is that possible?

FYI as a workaround I currently built a method "hasRole(String role)" which checks the role of the logged-in user, and throws a NotAuthorizedException (custom made) if the method returns false.

UserDetails

  @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;
  }

SecurityConfig

@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) {

Thanks!

解决方案

You can make use of Controller scoped Security with Spring HttpSecurity. Try add this to your configure Method:

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

And if you wish ANY Request to be public (really?):

.anyRequest().permitAll()

You can additionally secure your Methodinvocation for Example in your UserDetailsService when you access it from anywhere:

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

Only then you have to annotate your SecurityConfig with:

@EnableGlobalMethodSecurity(securedEnabled = true)

In practice we recommend that you use method security at your service layer, to control access to your application, and do not rely entirely on the use of security constraints defined at the web-application level. URLs change and it is difficult to take account of all the possible URLs that an application might support and how requests might be manipulated. You should try and restrict yourself to using a few simple ant paths which are simple to understand. Always try to use a"deny-by-default" approach where you have a catch-all wildcard ( / or ) defined last and denying access. Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security’s method security options.

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

这篇关于无法获取@Secured方法安全注解春季安全工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆