【问题标题】:using @PreAuthorize in Spring security with roles and rights在具有角色和权限的 Spring 安全性中使用 @PreAuthorize
【发布时间】:2014-10-27 12:29:54
【问题描述】:

我正在使用带有用户、角色、权限实体的 Spring Security,并且用户已成功通过身份验证,我可以访问其权限集合。

我使用 AJAX 调用视图页面并在前端和后端之间发送 json。问题是我不知道如何配置我的 spring-security 文件,因为 @PreAuthorize 注释不起作用。加载应用程序时会显示我的登录页面,如果从控制器以 json 格式发送的凭据错误,它会重定向到登录页面。如果您能帮我解决问题,我将不胜感激。

@PreAuthorize("hasRole('ROLE_RIGHT_READ_USER_LIST')")
//    @Secured("ROLE_RIGHT_READ_USER_LIST")
    @RequestMapping(value = "/findAll", method = RequestMethod.GET, produces = {"application/json"})
    @ResponseBody
    public String findAll(HttpServletRequest request) { 

这是我的 spring-security 文件内容:

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">

<global-method-security pre-post-annotations="enabled" secured-annotations="enabled"/>
    <http auto-config="true" use-expressions="true">

        <intercept-url pattern="/user/findAll/" access="hasRole('ROLE_RIGHT_READ_USER_LIST')" />

    </http>

<beans:bean id="jdbcAuthenticationProvider" class="com.my.app.spring.JdbcAuthenticationProvider"/>

    <authentication-manager>
        <authentication-provider ref="jdbcAuthenticationProvider"/>
    </authentication-manager>
</beans:beans>

这是我的控制器:

@Controller
@RequestMapping("/auth")
public class SecurityHandler extends AbstractHandler {

    @Autowired
    protected UserService userService;
    @Resource(name = "authenticationProvider")
    AuthenticationProvider authenticationProvider;

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = {"application/json"})
    @ResponseBody
    public String logon(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password,
            HttpServletRequest request) {


      Authentication req = new UsernamePasswordAuthenticationToken( username, password );
    Authentication result = authenticationProvider.authenticate( req );
    SecurityContextHolder.getContext().setAuthentication( result );

    UserDetails userDetails=null;
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (!(auth instanceof AnonymousAuthenticationToken)) {
                 userDetails
                        = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            }

    User user = (User)userDetails;


    Collection<? extends GrantedAuthority> ga = userDetails.getAuthorities();


            HttpSession session = request.getSession(true);
            session.setAttribute(SESSION_ATTRIB_USER, user);
            return getJsonSuccessData(user);

        } else {

            return getJsonErrorMsg(ar.getMsg());

        }

    }

【问题讨论】:

  • 虽然你的配置有一些重复,但似乎已经够用了。您确定要保护的控制器与 Spring Security 上下文属于同一上下文的一部分吗?
  • 是的,只有一个上下文。

标签: java spring-mvc spring-security authorization


【解决方案1】:

好的,我真的不知道您是如何配置上下文的,但是,我将在此处粘贴我正在使用的基于 Java 的配置:

import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;

import com.comilion.fw.app.security.MyPermissionEvaluator;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalMethodSecurityCtxConfiguration extends GlobalMethodSecurityConfiguration {

}

如果您使用基于 XML 的配置,只需使用

将其添加到您的配置中

【讨论】:

  • 这不等于我的xml配置吗?
猜你喜欢
  • 2015-10-28
  • 2011-09-15
  • 2010-10-26
  • 2011-12-15
  • 2013-10-06
  • 2012-12-25
  • 2011-02-12
  • 2016-11-16
相关资源
最近更新 更多