Spring-Security授权角色不起作用

时间:2017-08-31 12:31:16

标签: java spring spring-boot spring-security

尝试在我现有的Spring Boot系统中实现基于Spring Security的角色授权。我想根据某些用户授权限制REST API的访问。

为此,我创建了一个SpringConfiguration.java类,如下所示:

SecurityConfiguration.java

public class SecurityConfig_BasicAuth extends WebSecurityConfigurerAdapter {

   private static String REALM = "Test";

   @Autowired
   public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication().withUser("Deb").password("deb@123").roles("ADMIN"); // Line 1
      auth.inMemoryAuthentication().withUser("Bob").password("Bob@123").roles("USER"); // Line 2
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
      .csrf().disable()
      .authorizeRequests().antMatchers("/checkRoleBaseAuthorization/**")
      .hasRole("ADMIN").and() // Line 3
      .httpBasic().realmName(REALM)
      .authenticationEntryPoint(getBasicAuthEntryPoint()).and()
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
   }

   @Bean
   public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
      return new CustomBasicAuthenticationEntryPoint();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
   }
}

在上面的课程中,我使用授权角色ADMIN / USER定义了两个用户/密码。现在我想只允许那些具有ADMIN角色的用户。

如果凭据不匹配,则下面的类将返回状态401。

CustomBasicAuthenticationEntryPoint.java

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

   @Override
   public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException)
         throws IOException, ServletException {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

      PrintWriter writer = response.getWriter();
      writer.println("HTTP Status 401 : " + authException.getMessage());
   }

   @Override
   public void afterPropertiesSet() throws Exception {
      setRealmName("Test");
      super.afterPropertiesSet();
   }
}

REST API

   @RequestMapping(value = "/checkRoleBaseAuthorization", method = RequestMethod.GET)
   public String checkRoleBaseAuthorization() {
      return "checkRoleBaseAuthorization() Invoked";
   }

我的程序在某种程度上工作,即没有用户/密码,API无法访问。

  

但为什么我也可以使用Bob / Bob @ 123登录?它有角色“USER”,   不是我在SecurityConfiguration.java中指定的“ADMIN”(参见   第3行。

0 个答案:

没有答案