【问题标题】:Spring security set up access control with oauth2 tokenSpring Security 使用 oauth2 令牌设置访问控制
【发布时间】:2015-04-05 02:28:06
【问题描述】:

我正在发现 oauth2。我设法创建了一个示例,该示例返回受此令牌保护的 JWToken 和 REST。 现在我想通过在受保护的 REST 接口中添加访问控制来改进这一点。 为什么 ?因为我希望像 ADMIN 这样的用户,READER 访问某些 URL。

关注http://projects.spring.io/spring-security-oauth/docs/oauth2.html 可以通过 http 节点中的表达式处理程序。 这是我添加到我的 xml 配置中的配置:

<sec:global-method-security
    pre-post-annotations="enabled" />

<sec:http pattern="/protected/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint">
    <sec:anonymous enabled="false" />
    <sec:intercept-url pattern="/protected/**" />
    <sec:custom-filter ref="resourceServerFilter"
        before="PRE_AUTH_FILTER" />
    <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
    <sec:expression-handler ref="myexpressionHandler" />
</sec:http>

<bean id="myexpressionHandler" class="org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler"> 
</bean>

日志: 热火朝天2015 年 4 月 4 日下午 4:09:31 org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParser 解析 INFOS:为方法安全启用了表达式,但未配置 SecurityExpressionHandler。所有 hasPermision() 表达式的计算结果都为 false。 热火朝天2015 年 4 月 4 日下午 4:09:31 org.springframework.security.config.http.HttpSecurityBeanDefinitionParser checkFilterChainOrder

但是使用我的 JWTtoken,我成功获得了受保护的资源。

我的控制器:

@Component
@RestController
@RequestMapping(value = "/protected")
public class HelloWorldRest {

    private static final Logger LOG = LoggerFactory
            .getLogger(HelloWorldRest.class);

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @PreAuthorize("#oauth2.clientHasRole('ROLE_ADMIN')")
    @RequestMapping(value = "/greeting/{name}")
    public Greeting greeting(@PathVariable String name) {
        LOG.info("Fonction greeting : " + name);
        return new Greeting(counter.incrementAndGet(), String.format(template,
                name + ", I am Mister Toto"));
    }

}

我已经与获得 authorityGrant={ ROLE_NONE }

的用户进行了测试

谢谢, 有什么想法吗?

【问题讨论】:

    标签: spring-mvc oauth spring-security jwt


    【解决方案1】:

    为避免“SecurityExpressionHandler 已配置”错误消息,您应该将表达式处理程序添加到您的 global-method-security。像这样:

    <sec:global-method-security pre-post-annotations="enabled">
      <sec:expression-handler ref="oauthExpressionHandler" />
    </sec:global-method-security> 
    <oauth:expression-handler id="oauthExpressionHandler" />
    

    除了为 WebSecurityExpressionHandler 定义自己的 bean(正如您在问题中所做的那样),您还可以使用:

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />
    

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2023-03-03
      • 2020-08-19
      • 2016-05-04
      • 2018-05-06
      • 1970-01-01
      相关资源
      最近更新 更多